简体   繁体   English

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

[英]Syntax error while creating a trigger in PostgreSQL

I created a table name Student in PostgreSQL and then I tried defining a trigger on that table but it's showing an error message in doing so.我在 PostgreSQL 中创建了一个表名Student ,然后我尝试在该表上定义一个触发器,但它在这样做时显示了一条错误消息。

Trigger Syntax:触发语法:

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

Table Creation Command:表创建命令:

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

Actually I tried to declare the execution statements directly inside the trigger only rather than calling any procedure/ function from the trigger which is working fine but I want to do in this way in PostgreSQL.实际上,我试图仅在触发器内部直接声明执行语句,而不是从触发器中调用任何工作正常的过程/函数,但我想在 PostgreSQL 中以这种方式进行。

PostgreSQL doesn't support it. PostgreSQL 不支持它。 You need trigger function always.你总是需要触发功能。

As documented in the manual you need atrigger 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;

Not sure what you intend with the user parameter there, as that is not the table name, but the current database user.不确定您对那里的user参数的意图,因为那不是表名,而是当前的数据库用户。 If you want to display the actual table name, you need to use TG_RELNAME instead - which is an implicit variable available in the trigger function.如果要显示实际表名,则需要改用TG_RELNAME - 这是触发器函数中可用的隐式变量

And a trigger definition触发器定义

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM