How to raise error from PostgreSQL SQL statement if some condition is met?
I tried code below but got error.
CREATE OR REPLACE FUNCTION "exec"(text)
RETURNS text AS
$BODY$
BEGIN
EXECUTE $1;
RETURN $1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
-- ERROR: syntax error at or near "raise"
-- LINE 1: raise 'test'
SELECT exec('raise ''test'' ') WHERE TRUE
In real application TRUE is replaced by some condition.
Update
I tried to extend answer to pass exception message parameters.
Tried code below but got syntax error.
How to pass message parameters ?
CREATE OR REPLACE FUNCTION exec(text, variadic )
RETURNS void LANGUAGE plpgsql AS
$BODY$
BEGIN
RAISE EXCEPTION $1, $2;
END;
$BODY$;
SELECT exec('Exception Param1=% Param2=%', 'param1', 2 );
You cannot call
RAISEdynamically (withEXECUTE) in PL/pgSQL – that only works for SQL statements, andRAISEis a PL/pgSQL command.Use this simple function instead:
Call:
Related:
Additional answer to comment
Call:
VARIADICis not a data type, but an argument mode.Elements have to be handled like any other array element.
To use multiple variables in a
RAISEstatement, put multiple%into the message text.The above example will fail if no
$3is passed. You’d have to assemble a string from the variable number of input elements. Example:Call:
I doubt you need a
VARIADICparameter for this at all. Read the manual here.Instead, define all parameters, maybe add defaults:
Call:
Or: