How to execute PostgreSQL RAISE command dynamically

Viewed 36698

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 ); 
1 Answers
Related