问题描述
如果满足某些条件,如何引发PostgreSQL SQL语句的错误?
我尝试过下面的代码,但出现错误。
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
在实际应用中 TRUE
被某些条件所替代。
In real application TRUE
is replaced by some condition.
更新
我试图扩展答案传递异常消息参数。
尝试下面的代码,但语法错误。
如何传递消息参数?
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 );
推荐答案
您无法调用 RAISE
在PL / pgSQL中动态(使用 EXECUTE
) - 仅适用于SQL语句, RAISE
是一个PL / pgSQL命令。
You cannot call RAISE
dynamically (with EXECUTE
) in PL/pgSQL - that only works for SQL statements, and RAISE
is a PL/pgSQL command.
使用这个简单的函数:
CREATE OR REPLACE FUNCTION f_exec(text)
RETURNS void LANGUAGE plpgsql AS
$BODY$
BEGIN
RAISE EXCEPTION '%', $1;
END;
$BODY$;
致电:
SELECT f_exec('My message is empty!');
我在这个:功能调用等的功能说明,链接,更多选项,上下文(包括行号)
I wrote more in this related answer on dba.SE: explanation, links, more options for the function, context (including line number) from the function call etc.
CREATE OR REPLACE FUNCTION f_exec1(VARIADIC text[])
RETURNS void LANGUAGE plpgsql AS
$BODY$
BEGIN
RAISE EXCEPTION 'Reading % % %!', $1[1], $1[2], $1[3];
END;
$BODY$;
致电:
SELECT f_exec1('the','manual','educates');
-
VARIADIC
不是数据类型,而是 。
相反,定义所有参数,也可以添加默认值:I doubt you need a
VARIADIC
parameter for this at all. Read the manual here.
Instead, define all parameters, maybe add defaults:CREATE OR REPLACE FUNCTION f_exec3(_param1 text = '' ,_param2 text = '' ,_param3 text = 'educates') RETURNS void LANGUAGE plpgsql AS $BODY$ BEGIN RAISE EXCEPTION 'Reading % % %!', $1, $2, $3; END; $BODY$;
致电:
SELECT f_exec3('the','manual','educates'); SELECT f_exec3(); -- defaults kick in
这篇关于如何动态执行PostgreSQL RAISE命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!