Postgres无法创建触发器功能; 'RETURN'附近的语法错误'

时间:2016-05-29 11:05:10

标签: postgresql triggers ddl

我是一个postgres noob,想为我的管理员表创建一个触发器功能。 我正在关注一个在线的例子,检查了类似的问题,并尝试了各种在线示例,但我仍然卡住了。

我有一张表管理员

CREATE TABLE admins (
admin_name      varchar(15) PRIMARY KEY NOT NULL,
password        text NOT NULL,
telephone       varchar(15) NOT NULL UNIQUE,
email           varchar(30) NOT NULL UNIQUE,
added           timestamp DEFAULT CURRENT_TIMESTAMP,
name            varchar(30) NOT NULL,
active          boolean DEFAULT true     
);

审核表 aud_admins

CREATE TABLE aud_admins (
admin_name      varchar(15) PRIMARY KEY NOT NULL,
password        text NOT NULL,
telephone       varchar(15) NOT NULL UNIQUE,
email           varchar(30) NOT NULL UNIQUE,
added           timestamp DEFAULT CURRENT_TIMESTAMP,
name            varchar(30) NOT NULL,
active          boolean DEFAULT true,
updated         timestamp DEFAULT CURRENT_TIMESTAMP,  
func            varchar(15)  NOT NULL     
);
  • 我正在尝试创建一个存储的触发器功能,以便在发生更改时更新 aud_admins 表但是可悲地失败

这是我的触发功能代码:

CREATE OR REPLACE FUNCTION public.audit_admins()
RETURNS trigger AS
$BODY$
BEGIN 
IF (TG_OP = 'DELETE') THEN
    INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) VALUES (OLD.admin_name,OLD.password,OLD.telephone,OLD.email,OLD.added,OLD.name,OLD.active,PG_OP)
    RETURN OLD;
ENDIF;
IF (TG_OP = 'INSERT') THEN
     INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) VALUES (NEW.admin_name,NEW.password,NEW.telephone,NEW.email,NEW.added,NEW.name,NEW.active,PG_OP)
     RETURN NEW;
ENDIF;
IF (TG_OP = 'UPDATE') THEN
    INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) VALUES (OLD.admin_name,OLD.password,OLD.telephone,OLD.email,OLD.added,OLD.name,OLD.active,PG_OP)
    RETURN NEW;
ENDIF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

每次我运行它都会出现此错误

**ERROR:  syntax error at or near "RETURN"
  LINE 7:         RETURN OLD;**

基本运行时规范:

  

Postgres 9.5 on   Ubuntu 16.04   用pgAdmin3

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您的INSERT语句不会以分号结尾。尝试更新到以下内容:

IF (TG_OP = 'DELETE') THEN
    INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) 
    SELECT OLD.admin_name,OLD.password,OLD.telephone,OLD.email,OLD.added,OLD.name,OLD.active,PG_OP;
    RETURN OLD;
END IF;
IF (TG_OP = 'INSERT') THEN
     INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) 
     SELECT NEW.admin_name,NEW.password,NEW.telephone,NEW.email,NEW.added,NEW.name,NEW.active,PG_OP;
     RETURN NEW;
END IF;
IF (TG_OP = 'UPDATE') THEN
    INSERT INTO aud_admins (admin_name,password,telephone,email,added,name,active,func) 
    SELECT OLD.admin_name,OLD.password,OLD.telephone,OLD.email,OLD.added,OLD.name,OLD.active,PG_OP;
    RETURN NEW;
END IF;

更新了插入内容,我认为您需要使用INSERT实际SELECT。尝试修改上面的代码。