sql – 在插入访问NEW后的Postgres触发器

我有一个很简单的触发器:
CREATE OR REPLACE FUNCTION f_log_datei()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO logs (aktion,tabelle,benutzer_id) VALUES(TG_OP,'dateien',NEW.benutzer_id);
END; $$LANGUAGE 'plpgsql';

CREATE TRIGGER log_datei AFTER INSERT OR UPDATE OR DELETE
ON dateien
FOR EACH STATEMENT
EXECUTE PROCEDURE f_log_datei();

我的桌面日志如下:

CREATE TABLE logs(
    id int PRIMARY KEY DEFAULT NEXTVAL('logs_id_seq'),zeit timestamp DEFAULT now(),aktion char(6),tabelle varchar(32),alt varchar(256),neu varchar(256),benutzer_id int references benutzer(id)
);

在dateien中插入某些东西后,我会收到以下错误信息:

ERROR:  record "new" is not assigned yet
DETAIL:  The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT:  sql statement "INSERT INTO logs (aktion,NEW.benutzer_id)"
PL/pgsql function "f_log_datei" line 3 at sql statement

为什么我得到这个错误?我查看了文档,似乎他们以同样的方式使用新的文件.

解决方法

fine manual

36.1. Overview of Trigger Behavior
[…]
For a row-level trigger,the input data also includes the NEW row for INSERT and UPDATE triggers,and/or the OLD row for UPDATE and DELETE triggers. Statement-level triggers do not currently have any way to examine the individual row(s) modified by the statement.

Trigger Procedures

NEW
Data type RECORD; variable holding the new database row for INSERT/UPDATE operations in row-level triggers. This variable is NULL in statement-level triggers and for DELETE operations.

请注意它对行级触发器和语句级触发器的说明.

您有一个语句级触发器:

...
FOR EACH STATEMENT
EXECUTE PROCEDURE f_log_datei();

语句级触发器每个语句触发一次,并且语句可以应用于多个行,因此受影响的行(这是NEW和OLD关于)的概念根本不适用.

如果要在触发器中使用NEW(或OLD),则希望为每个受影响的行执行触发器,这意味着您需要一个行级触发器:

CREATE TRIGGER log_datei AFTER INSERT OR UPDATE OR DELETE
ON dateien
FOR EACH ROW
EXECUTE PROCEDURE f_log_datei();

我刚刚将每个声明改为“每一个道路”.

你的触发器也应该是be returning something

A trigger function must return either NULL or a record/row value having exactly the structure of the table the trigger was fired for.
[…]
The return value of a row-level trigger fired AFTER or a statement-level trigger fired BEFORE or AFTER is always ignored; it might as well be null. However,any of these types of triggers might still abort the entire operation by raising an error.

所以你应该返回新的或返回NULL;在你的触发器.你有一个AFTER触发器,所以你使用哪个RETURN并不重要,但我会与RETURN NEW;

相关文章

(一)日志传送架构 (1.1)相关服务器 主服务器 :用于生产的服务器,上面运行这生产SQL Server数据库...
(一)事故背景 最近在SQL Server 2012生产数据库上配置完事物复制(发布订阅)后,生产数据库业务出现了...
(一)测试目的 目前公司使用的SQL SERVER 2012高可用环境为主备模式,其中主库可执行读写操作,备库既...
(一)背景个人在使用sql server时,用到了sql server的发布订阅来做主从同步,类似MySQL的异步复制。在...
UNION和OR谓词 找出 product 和 product2 中售价高于 500 的商品的基本信息. select * from product wh...
datawhale组队学习task03