Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get PL PGSQL error code in a function?

I am writing a PL/PGSQL function and it produces an error. I want to print the error with RAISE NOTICE statement but I don't know how to get the error code? What variable holds the last error?

This is my sample code:

IF FOUND
THEN
    BEGIN
        insert into app.company(dateinserted,name) values(now(),company_name) returning comnpany_id;
        return company_id;
    EXCEPTION
        WHEN OTHERS THEN
            RAISE NOTICE 'Insert failed with...';
            return -2;
    END;
ELSE
    RETURN -1;
END IF;

This code will return company_id if insert was successful and print the error if it fails.

like image 510
Nulik Avatar asked Aug 02 '26 03:08

Nulik


1 Answers

...
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'Insert failed with error code %', SQLSTATE;
...

Read more in the documentation.

like image 60
klin Avatar answered Aug 04 '26 18:08

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!