简体   繁体   English

触发器内有多个insert / update语句?

[英]Multiple insert/update statements inside trigger?

Just a quick question that no doubt someone out there will know the answer to. 只是一个简单的问题,毫无疑问,有人会知道答案。

I need to be able to do multiple insert/updates within a trigger. 我需要能够在触发器中进行多次插入/更新。 Every attempt ends with failure :( 每次尝试都以失败结束:(

DROP TRIGGER IF EXISTS `Insert_Article`//
CREATE TRIGGER `Insert_Article` AFTER INSERT ON `Article`
 FOR EACH ROW insert into FullTextStore (`Table`, `PrimaryKey`, `ColumnName`, `Data`, `Created`) values ('Article', NEW.ArticleID, 'Description', NEW.Description, UNIX_TIMESTAMP())
//

At the moment, the above simply inserts a row into a table when the parent table inserts. 目前,上面只是在父表插入时将一行插入表中。 This works fine. 这很好用。

To get this to work with mulitple values I need to do 要使这与多个值一起工作,我需要做

DROP TRIGGER IF EXISTS `Insert_Article`//
CREATE TRIGGER `Insert_Article` AFTER INSERT ON `Article`
 FOR EACH ROW insert into FullTextStore (`Table`, `PrimaryKey`, `ColumnName`, `Data`, `Created`)
select 'Article', NEW.ArticleID, 'Description', NEW.Description, UNIX_TIMESTAMP()
union
select 'Article', NEW.ArticleID, 'Keywords', NEW.Keywords, UNIX_TIMESTAMP()
//

But... There must be an easier way? 但是......必须有一个更简单的方法吗? When I try using ; 当我尝试使用; to terminate each statement, it fails with 为了终止每个语句,它失败了

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL version for the right syntax to use near 'select 'Article', NEW.ArticleID, 'Keywords', 'NEW.Keywords, UNIX_TIMESTAMP())' at line 1

I can't even get multiple update statements to work. 我甚至无法获得多个更新语句。

It'd be a great help if anyone could point out what i'm doing wrong? 如果有人能指出我做错了什么,这将是一个很大的帮助?

Cheers 干杯

Gavin 加文

From the docs: Create Trigger Syntax 从文档: 创建触发器语法

trigger_stmt is the statement to execute when the trigger activates. trigger_stmt是触发器激活时要执行的语句。 If you want to execute multiple statements, use the BEGIN ... END compound statement construct. 如果要执行多个语句,请使用BEGIN ... END复合语句构造。 This also enables you to use the same statements that are allowable within stored routines 这也使您可以使用存储例程中允许的相同语句

CREATE TRIGGER testref BEFORE INSERT ON test1
  FOR EACH ROW BEGIN
    INSERT INTO test2 SET a2 = NEW.a1;
    DELETE FROM test3 WHERE a3 = NEW.a1;
    UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
  END;

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

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