简体   繁体   中英

How to raise an error with PostgreSQL select statement?

I need to create a data patching script and I'd like to rollback the transaction when some condition occurs.

I could do something like this in the end of the script:

select t.id / 0
from some_table t
where t.state = 'undersirable state'

but I'd rather have a more appropriate error message than "division by zero".

Is there a generic function for generating errors in PostgreSQL? I'd like to do it without PL/SQL, if possible.

Write a little function that raises the error for you and use that in your SELECT statement.

CREATE FUNCTION raise_error() RETURNS integer
   LANGUAGE plpgsql AS
$$BEGIN
   RAISE EXCEPTION /* whatever you want */;
   RETURN 42;
END;$$;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM