為此,語法如下 –
delimiter // create trigger yourTriggerName before insert on yourTableName FOR EACH ROW BEGIN yourStatement1 . . N END // delimiter ;
登錄后復制
為了理解上述語法,讓我們創建一個表 –
mysql> create table DemoTable1919 ( Value int ); Query OK, 0 rows affected (0.00 sec)
登錄后復制
這是在插入之前創建 MySQL 觸發器的查詢 –
mysql> delimiter // mysql> create trigger sumis60 before insert on DemoTable1919 FOR EACH ROW BEGIN declare custom_message varchar(256); IF (SELECT sum(Value) from DemoTable1919) = 60 THEN set custom_message= "cannot insert because sum(Value) is greater than 60"; signal sqlstate '13500' set message_text= custom_message; END IF; END // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ;
登錄后復制
現在您可以使用插入命令在表中插入一些記錄并檢查觸發器的工作 –
mysql> insert into DemoTable1919 values(10); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(20); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(30); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1919 values(40); ERROR 1644 (13500): cannot insert because sum(Value) is greater than 60
登錄后復制
以上就是如何在插入之前創建MySQL觸發器?的詳細內容,更多請關注www.92cms.cn其它相關文章!