首頁 >資料庫 >mysql教程 >如何在插入之前建立MySQL觸發器?

如何在插入之前建立MySQL觸發器?

PHPz
PHPz轉載
2023-08-29 14:09:061024瀏覽

如何在插入之前建立MySQL觸發器?

為此,語法如下-

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觸發器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除