PostgreSQL 使用变量名作为字符串文字

PostgreSQL using variable name as string literal

在此脚本中,我希望输出为:

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 to use a variable in this case. See also this post.