关于sql触发器语法的问题

bakd9h0s  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(338)

我想创建一个触发器,在对特定表执行insert之后,有两个条件,如果第一个条件为true,则执行insert,如果第二个条件为true,则执行update。
类似的东西:

create trigger nameoftrigger

after insert on a

for each row
condition regarding newrowattribute and a.sameattribute

insert into a ---

condition regarding newrowattribute and a.sameattribute

update a different table with same attributes

但我不知道这样做的正确语法,检查两个不同的条件,在第一个条件中执行插入,在第二个条件中执行更新。

9rygscc1

9rygscc11#

mysql不支持像microsoftsqlserver那样的“代替”触发器。
insert触发器可以执行插入操作,否则它将中止而不执行任何操作。
您应该在应用程序代码中处理您的条件。
raymond nijland提醒我,您也不能编写对执行触发器的表执行任何插入或更新的触发器。你可以创建这样一个触发器,但是当它执行时会产生一个错误。

mysql> create trigger nameoftrigger after insert on a for each row 
  insert into a values (1);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into a values (2);
ERROR 1442 (HY000): Can't update table 'a' in stored function/trigger because 
it is already used by statement which invoked this stored function/trigger.
bttbmeg0

bttbmeg02#

看到了吗 IF ... THEN ... ELSE ... END IF 对于控制流。
如果要修改要插入的内容,请执行以下操作

IF (...) 
THEN
    SET NEW.col1 = <<some expression>>;
END IF

那就让 INSERT 发生。
如果if表达式或col1的表达式需要查看 INSERT 对于col1,则将其称为 OLD.col1 .

相关问题