How to apply 'if sqlcode' in oracle to postgres?

129 Views Asked by At

code in oracle

parameter info = in iv_column_1, in iv_column_2, inout iv_msg

begin 
  update main_table set column_1 = iv_column_1 where column_2 = 
  iv_colmun_2;
  if sqlcode <> 0 then
    iv_msg := 'main_table error '||CHR (13)||CHR (10)||SQLERRM;
    return;
  end if;
  insert into history_table (column_1 , column_2) values (iv_column_1, 
  iv_column_2);
    if sqlcode <> 0 then
    iv_msg := 'history_table error '||CHR (13)||CHR (10)||SQLERRM;
    return;
  end if;

code in postgresql

parameter info = in iv_column_1, in iv_column_2, inout iv_msg

begin 
  update main_table set column_1 = iv_column_1 where column_2 = 
  iv_colmun_2;
  if sqlstate <> 0 then
    iv_msg := 'main_table error '||CHR (13)||CHR (10)||SQLERRM;
    return;
  end if;
  insert into history_table (column_1 , column_2) values (iv_column_1, 
  iv_column_2);
    if sqlstate <> 0 then
    iv_msg := 'history_table error '||CHR (13)||CHR (10)||SQLERRM;
    return;
  end if;

error text :

SQL Error [42703]: ERROR: column "sqlstate" does not exist

1

There are 1 best solutions below

2
Belayer On

The Postgres equivalent of Oracle's sqlcode 0 is the global variable FOUND (see Basic Statements:Table 43.1. Available Diagnostics Items. It is set by each of the following types of statements:

UPDATE, INSERT, DELETE, and MERGE statements set FOUND true if at least one row is affected, false if no row is affected.

So your code becomes:

begin 
  update main_table set column_1 = iv_column_1 where column_2 = 
  iv_colmun_2;
  if not FOUND then
    iv_msg := E'main_table error \n ' ||SQLERRM;
    return;
  end if;
  insert into history_table (column_1 , column_2) values (iv_column_1, 
  iv_column_2);
  if not FOUND then
    iv_msg := E'history_table error \n ' ||SQLERRM;
    return;
  end if;

Assuming this is just part of a larger block. If an error occurs on the insert Postgres will most likely throw an exception, in which case a EXCEPTION segment of the block is required. As others have indicated.
NOTE: Not tested as no data provided.