MySQL is not like some other databases can throw exceptions in triggers to interrupt the execution of course triggers to prevent the execution of the corresponding SQL statement. It is not possible to throw exceptions directly in the MySQL directory version. So how do we do it?
The following is an implementation method. The idea is to try to interrupt the execution of the code by using an error statement in the trigger.
Mysql> Create TableT_control (IDInt Primary Key);
Query OK,0Rows Affected (0.11Sec
Mysql> Insert IntoT_controlValues(1);
Query OK,1Row affected (0.05Sec
Mysql> Create TableT_bluerosehero (IDInt Primary Key, colInt);
Query OK,0Rows Affected (0.11Sec
Mysql>Delimiter//
Mysql> Create TriggerTr_t_bluerosehero_bi beforeInsert OnT_bluerosehero
- ForEach row
- Begin
-IfNew.col>30 Then
-Insert IntoT_controlValues(1);
-End If;
- End;
- //
Query OK,0Rows Affected (0.08Sec
Mysql>delimiter;
Mysql>
Mysql> Insert IntoT_blueroseheroValues(1,20);
Query OK,1Row affected (0.25Sec
Mysql> Insert IntoT_blueroseheroValues(2,40);
ERROR1062(23000): Duplicate Entry‘1‘ For Key ‘PRIMARY‘
Mysql>
Mysql> Select * FromT_bluerosehero;
+----+------+
|Id|Col|
+----+------+
| 1 | |
+----+------+
1 Row in Set (0.00 sec) mysql>
Or
Mysql>Delimiter//
Mysql> Create TriggerTr_t_bluerosehero_bi beforeInsert OnT_bluerosehero
- ForEach row
- Begin
-DeclareIInt;
-IfNew.col>30 Then
-Insert IntoXxxxValues(1);
-End If;
- End;
- //
Query OK,0Rows Affected (0.06Sec
Mysql>delimiter;
Mysql> Delete FromT_bluerosehero;
Query OK,3Rows Affected (0.05Sec
Mysql> Insert IntoT_blueroseheroValues(1,20);
Query OK,1Row affected (0.06Sec
Mysql> insert into T_bluerosehero Values2 ,40 );
ERROR 1146 (42S02): table csdn.xxxx< Span style= "color: #ff0000;" > '
How do I interrupt the insertion or update of a record in a trigger in MySQL?