MySQL使用DELIMITER $$创建触发器语法错误

时间:2018-11-24 14:18:25

标签: mysql triggers

我试图通过此代码防止列上的值重复,但出现语法错误:

  

如果存在(从第1行的tbl_baivietsp t'中选择*

DELIMITER $$
CREATE TRIGGER key_as_linksp ON tbl_baivietsp
AFTER INSERT
AS
if exists ( select * from tbl_baivietsp t inner join INSERTED i on i.LINK_SP 
LIKE CONCAT('%', t.LINK_SP ,'%'))
begin
  rollback TRANSACTION
  RAISERROR ('Duplicate Data', 16, 1);
end
go
$$
DELIMITER ;

下班后真的不知道问题出在哪里,多谢您的协助!

1 个答案:

答案 0 :(得分:1)

您已在TSQL(Microsoft SQL Server)中编写了触发器代码;但是,您正在使用MySQL。建议在以下位置查看触发器文档:https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

DELIMITER $$

/* AFTER INSERT comes before the table name on which Trigger is being created */
CREATE TRIGGER key_as_linksp AFTER INSERT ON tbl_baivietsp

FOR EACH ROW BEGIN /* Instead of AS, Trigger block starts with FOR EACH ROW BEGIN */

  IF EXISTS ( select 1 from tbl_baivietsp t 
              inner join INSERTED i 
                on i.LINK_SP LIKE CONCAT('%', t.LINK_SP ,'%')) THEN /* THEN is missing */
      /* Throw Exception */
      SIGNAL SQLSTATE '45000' 
        SET MESSAGE_TEXT = 'Duplicate Data';
  END IF; /* we use END IF instead of END to end an IF block */

END $$  /* Trigger block ends with END clause */
DELIMITER ;

对于MySQL,我们使用SIGNAL .. SET MESSAGE_TEXT ..在触发器内引发异常。