How do I interrupt the insertion or update of a record in a trigger in MySQL?

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.