在此脚本中,我期望输出为:
NOTICE: 00000: Outside value is: hello
NOTICE: 00000: Inside value is: hello
但是输出是:
NOTICE: 00000: Outside value is: hello
NOTICE: 00000: Inside value is: my_variable
为什么 PostgreSQL 在将变量传递给函数时使用变量名称作为字符串文字?请注意,我没有在变量名称两边加上单引号,因此我并不期望它被解释为字符串文字。
这是脚本:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table(my_field text);
CREATE OR REPLACE FUNCTION my_function() RETURNS TRIGGER AS $$
BEGIN
RAISE NOTICE 'Inside value is: %', TG_ARGV[0];
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DO $$
DECLARE
my_variable text := 'hello';
BEGIN
RAISE NOTICE 'Outside value is: %', my_variable;
CREATE TRIGGER my_trigger
AFTER INSERT ON my_table
FOR EACH ROW
EXECUTE PROCEDURE my_function(my_variable);
END
$$;
INSERT INTO my_table VALUES('some value');
最佳答案
来自the documentation (强调):
arguments
An optional comma-separated list of arguments to be provided to the function when the trigger is executed. The arguments are literal string constants. Simple names and numeric constants can be written here, too, but they will all be converted to strings.
CREATE TRIGGER 是一个 DDL 命令,其中变量未知。您需要dynamic SQL在这种情况下使用变量。另请参阅this post.
关于PostgreSQL 使用变量名作为字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989594/