ERROR_NUMBER Function - SQL Server to PostgreSQL Migration

In SQL Server, the ERROR_NUMBER function returns the error code of an exception and can only be used within a CATCH block.

In PostgreSQL, you can use the SQLSTATE variable, which contains the error code of the most recent exception. Note that the error code can be different for the same error in SQL Server and PostgreSQL.

SQL Server:

  CREATE TABLE t1 (c1 INT NOT NULL);
 
  BEGIN TRY
     -- Try to insert NULL into non-nullable column
     INSERT INTO t1 VALUES (NULL); 
  END TRY  
  BEGIN CATCH
    PRINT 'Error number: ' + STR(ERROR_NUMBER())
  END CATCH 
  /* Error number: 515 */

PostgreSQL:

  CREATE TABLE t1 (c1 INT NOT NULL);
 
  DO $$
  BEGIN
     -- Try to insert NULL into non-nullable column
     INSERT INTO t1 VALUES (NULL); 
  EXCEPTION WHEN OTHERS THEN
    RAISE NOTICE '%','Error number: ' || SQLSTATE;
  END; $$;
  /* Error number: 23502 */

For more information, see SQL Server to PostgreSQL Migration.