Postgres:如何从触发器获取动态列的值

时间:2014-09-17 20:07:20

标签: dynamic triggers postgresql-9.3

我试图获取列的值,以便可以将其插入到包含插入行的列名和列值的表中,但是,我无法获取列的值我需要。通常,我可以使用value := NEW.column_name但是每个表都有一个唯一的键列名,它在表名中(我知道,这很糟糕),但我已经有办法获得列名了想要,它正在获得该列的新值,这就是问题所在。

    CREATE OR REPLACE FUNCTION trgfn_keyvalue_insert()
    RETURNS trigger AS
    $BODY$
    DECLARE
       key_column_value character varying;
       key_column_name character varying;
       part text;
       part_array text[] := array['prefix_','_suffix'];
    BEGIN    
       key_column_name := TG_TABLE_NAME;     --parsing the table name to get the desired column name
       FOREACH part IN ARRAY part_array LOOP
          key_column_name = regexp_replace(cat, part, '');
       END loop; 

       IF TG_OP = 'INSERT' THEN    
       EXECUTE 'SELECT $1 FROM $2'           --This is where I'd like to get the 
          INTO key_column_value              --value of the column
          USING key_column_name, NEW;    

       INSERT INTO inserted_kvp
          (table_name, key, value)
          VALUES 
          (TG_TABLE_NAME, key_column_name, key_column_value);
       END IF;

       RETURN NEW;
    END;
    $BODY$
       LANGUAGE plpgsql VOLATILE

所以,当我插入表格时:

    CREATE TABLE prefix_kvp1_suffix AS id SERIAL, kvp1 CHARACTER VARYING;
    CREATE TABLE prefix_kvp2_suffix AS id SERIAL, kvp2 CHARACTER VARYING;

    INSERT INTO prefix_kvp1_suffix VALUES (1, 'value1');
    INSERT INTO prefix_kvp2_suffix VALUES (1, 'value2');

我希望inserted_kvp表格具有以下内容:

    |    table_name    |key |value |
    --------------------------------
    |prefix_kvp1_suffix|kvp1|value1|
    |prefix_kvp2_suffix|kvp2|value2|

相反,插入时出现以下错误:

    ERROR:  syntax error at or near "$2"
    LINE 1: SELECT $1 FROM $2
                   ^
    QUERY:  SELECT $1 FROM $2
    CONTEXT:  PL/pgSQL function worldmapkit.trgfn_keyvalue_insert() line 13 at EXECUTE statement

我尝试过使用EXECUTE format()以及其他一些方法来获取此值的不同变体,但我仍然没有运气。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:5)

经过多次摆弄,我找到了问题的答案。上面的EXECUTE语句的正确语法是:

    EXECUTE format('SELECT $1.%I', key_column_name) 
    INTO key_column_value
    USING NEW;

这将获得NEW记录的列值。希望这能帮助处于类似情况的人。