mysql内的if语句触发

时间:2020-05-25 20:26:53

标签: mysql sql if-statement sql-insert database-trigger

因此,我有两个表Practice和Practice1,其中两个表都具有自动增量ID以及名称和姓氏列。 我做了一个插入后触发器,其中有一个if语句,在其中放置了一个条件,如果名称为null,则应该插入一个,如果姓为null,则另一个插入,但是由于某种原因它不起作用。我正在分享我尝试过的脚本。

CREATE DEFINER = CURRENT_USER TRIGGER `id_information`.`practice_after_INSERT1` AFTER INSERT ON `practice` FOR EACH ROW
BEGIN
if (`name`  = NULL) then
 insert into id_information.practice1(surname) values(new.surname);
 else
 (`surname` = NULL) then
  insert into id_information.practice1(name) values(new.name);
 end if;
END$$
delimiter ;

请纠正我的错误。 id_information是数据库的名称。

1 个答案:

答案 0 :(得分:0)

我认为您想要的语法是:

delimiter $$

create definer = current_user trigger `id_information`.`practice_after_insert1` 
after insert on `practice` for each row
begin
    if new.name is null then
        insert into id_information.practice1(surname) values(new.surname);
    elseif new.surname is null then
        insert into id_information.practice1(name) values(new.name);
    end if;
end$$

delimiter ;

要点:

  • 您需要使用伪表new访问刚刚插入的行

  • 您的if语句的结构应为if ... then ... elseif ... end

  • 要根据null来检查值,请使用is null而不是= null(这永远是不正确的)