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

标签 postgresql triggers plpgsql

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

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/

相关文章:

node.js - 如何在 sequelize 中进行多个查询?

postgresql - 在 PostgreSQL 中递归聚合父级

PostgreSQL 错误 : EXECUTE of SELECT . .. INTO 未实现

postgresql - 根据输入数据填充 x、y 或 long、lat 字段,并根据输入创建点

sql - 编写/调试复杂 PL/pgSQL 查询的最佳实践

postgresql - 返回数据库结果集的PlPgsql函数

sql - 从复杂的选择创建 View

sql - Oracle数据库-确定哪个表触发了触发器

postgresql - 在表中保留一定数量的记录

javascript - jquery 两个具有相同类的不同触发器