在PostgreSQL中创建触发器时出现语法错误

时间:2020-11-03 04:38:43

标签: postgresql plpgsql

我在PostgreSQL中创建了一个表名 Student ,然后尝试在该表上定义一个触发器,但这样做会显示错误消息。

触发器语法:

CREATE TRIGGER bi_Student BEFORE INSERT ON Student as $$ 
FOR EACH ROW
BEGIN
    raise notice 'Successfully inserted into table(%)', user;   
end $$;

表创建命令:

create table Student(Stu_id int, Stu_Name text, Stu_Age int, Stu_address char(30));

实际上,我试图仅在触发器内部直接声明执行语句,而不是从触发器中调用任何过程/函数,效果很好,但我想在PostgreSQL中这样做。

2 个答案:

答案 0 :(得分:2)

PostgreSQL不支持它。您始终需要触发功能。

答案 1 :(得分:0)

As documented in the manual,您需要一个trigger function

create function my_trigger_function()
  returns trigger
as
$$
begin
  raise notice 'Successfully inserted into table(%)', user;   
  return new; --<< important (see the manual for details)
end
$$
language plpgsql;

不确定在那里使用user参数的意图,因为它不是表名,而是当前的数据库用户。如果要显示实际的表名,则需要使用TG_RELNAME-触发功能中的implicit variable

还有一个trigger definition

CREATE TRIGGER bi_Student 
BEFORE INSERT ON Student 
FOR EACH ROW
execute function my_trigger_function();