Question

How to check the error within the function of PostgreSQL?

My try for the same as shown below in the example.

Example:

create or replace function fun_testing(sn int, na text, gen text, ad text, rn int, flag int)
returns int as
$$
begin
if flag = 1 then
    insert into testing(ssn,name,gender,address,rno) values(sn,na,gen,ad,rn);

elsif flag = 2 then
    update testing
    set ssn=sn,
    name=na,
    gender=gen,
    address=ad,
    rno = rn
    where ssn=sn;

elsif flag =3 then
    delete from testing
    where ssn =sn;

end if;

if error <> 0 then /* Error Testing */ 
    return(1);
else
    return(0);
end if;
end;
$$
language plpgsql;

ERROR: column "error" does not exist

Note: The same if condition(using @@error) works fine with SQL Server but not getting executed in PostgreSQL.

Was it helpful?

Solution

You need a BEGIN ... EXCEPTION ... END block.

create or replace function fun_testing(sn int, na text, gen text, ad text, rn int, 
flag int)
returns int as
$$
begin
if flag = 1 then
    insert into testing(ssn,name,gender,address,rno) values(sn,na,gen,ad,rn);

elsif flag = 2 then
    update testing
    set ssn=sn,
    name=na,
    gender=gen,
    address=ad,
    rno = rn
    where ssn=sn;

elsif flag =3 then
    delete from testing
    where ssn =sn;

end if;

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;
end;


$$ language 'plpgsql';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top