在程序触发器中动态插入记录

Insert record dynamically inside of Procedural Trigger

我们正在寻求将我们的数据库转换为 Postgres (9.3.5),我对此没有任何经验,我正在努力使我们的审计 table 启动并 运行 宁.我知道每个 table 都需要自己的触发器,但所有触发器都可以调用一个函数。

table 上的触发器正在传递需要审计的列列表,因为我们的某些列未被跟踪。

以下是我关注的一些帖子:
-
- http://www.postgresql.org/docs/9.3/static/plpgsql-statements.html
- http://www.postgresql.org/docs/9.4/static/plpgsql-trigger.html

当我 运行 出现此错误时:错误:“$1”处或附近的语法错误

DROP TABLE IF EXISTS people;
DROP TABLE IF EXISTS a_people;

CREATE TABLE IF NOT EXISTS people (
  record_id  SERIAL PRIMARY KEY NOT NULL,
  first_name VARCHAR NOT NULL,
  last_name VARCHAR NOT NULL,
  last_updated_on TIMESTAMP NOT NULL DEFAULT  CURRENT_TIMESTAMP 
);

CREATE TABLE IF NOT EXISTS a_people (
  record_id  SERIAL PRIMARY KEY NOT NULL,
  a_record_id INT,
  first_name VARCHAR NULL,
  last_name VARCHAR NULL,
  last_updated_on TIMESTAMP
);
/******************************************************/
--the function
CREATE OR REPLACE FUNCTION audit_func()
RETURNS TRIGGER AS 
$BODY$  
    DECLARE 
        audit   TEXT := TG_TABLE_SCHEMA || '.a_' || TG_TABLE_NAME;
        cols    TEXT := TG_ARGV[0];
    BEGIN
        EXECUTE format('INSERT INTO %1$s(a_%2$s) SELECT %2$s FROM ()',  audit, cols) USING OLD;   
        NEW.last_updated_on = CURRENT_TIMESTAMP;
        RETURN NEW;
    END;
$BODY$
LANGUAGE plpgsql;
/******************************************************/
--the trigger calling the function to update inbound records
CREATE TRIGGER build_user_full_name_trg 
BEFORE UPDATE
ON people 
FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE PROCEDURE audit_func('record_id,first_name,last_name');
/******************************************************/
INSERT INTO people (first_name, last_name) VALUES ('George','Lincoln');
UPDATE people SET last_name = 'Washington' WHERE first_name = 'George';
SELECT * FROM people;

欢迎您的帮助(和耐心)!

这个子选择应该有效:

EXECUTE format('INSERT INTO %1$s(a_%2$s) SELECT %2$s FROM (select ().*) XX',  audit, cols) USING OLD;