MySQL 在触发器里中断记录的插入或更新?
程序员文章站
2023-12-12 20:13:34
下面是一种实现的方法。思路就是想办法在触发器中利用一个出错的语句来中断代码的执行。 mysql> create table t_control(id int prim...
下面是一种实现的方法。思路就是想办法在触发器中利用一个出错的语句来中断代码的执行。
mysql> create table t_control(id int primary key);
query ok, 0 rows affected (0.11 sec)
mysql> insert into t_control values (1);
query ok, 1 row affected (0.05 sec)
mysql> create table t_bluerosehero(id int primary key,col int);
query ok, 0 rows affected (0.11 sec)
mysql> delimiter //
mysql> create trigger tr_t_bluerosehero_bi before insert on t_bluerosehero
-> for each row
-> begin
-> if new.col>30 then
-> insert into t_control values (1);
-> end if;
-> end;
-> //
query ok, 0 rows affected (0.08 sec)
mysql> delimiter ;
mysql>
mysql> insert into t_bluerosehero values (1,20);
query ok, 1 row affected (0.25 sec)
mysql> insert into t_bluerosehero values (2,40);
error 1062 (23000): duplicate entry '1' for key 'primary'
mysql>
mysql> select * from t_bluerosehero;
+----+------+
| id | col |
+----+------+
| 1 | 20 |
+----+------+
1 row in set (0.00 sec)
mysql>
或者
mysql> delimiter //
mysql> create trigger tr_t_bluerosehero_bi before insert on t_bluerosehero
-> for each row
-> begin
-> declare i int;
-> if new.col>30 then
-> insert into xxxx values (1);
-> end if;
-> end;
-> //
query ok, 0 rows affected (0.06 sec)
mysql> delimiter ;
mysql> delete from t_bluerosehero;
query ok, 3 rows affected (0.05 sec)
mysql> insert into t_bluerosehero values (1,20);
query ok, 1 row affected (0.06 sec)
mysql> insert into t_bluerosehero values (2,40);
error 1146 (42s02): table 'csdn.xxxx' doesn't exist
mysql>
mysql> create table t_control(id int primary key);
query ok, 0 rows affected (0.11 sec)
mysql> insert into t_control values (1);
query ok, 1 row affected (0.05 sec)
mysql> create table t_bluerosehero(id int primary key,col int);
query ok, 0 rows affected (0.11 sec)
mysql> delimiter //
mysql> create trigger tr_t_bluerosehero_bi before insert on t_bluerosehero
-> for each row
-> begin
-> if new.col>30 then
-> insert into t_control values (1);
-> end if;
-> end;
-> //
query ok, 0 rows affected (0.08 sec)
mysql> delimiter ;
mysql>
mysql> insert into t_bluerosehero values (1,20);
query ok, 1 row affected (0.25 sec)
mysql> insert into t_bluerosehero values (2,40);
error 1062 (23000): duplicate entry '1' for key 'primary'
mysql>
mysql> select * from t_bluerosehero;
+----+------+
| id | col |
+----+------+
| 1 | 20 |
+----+------+
1 row in set (0.00 sec)
mysql>
或者
mysql> delimiter //
mysql> create trigger tr_t_bluerosehero_bi before insert on t_bluerosehero
-> for each row
-> begin
-> declare i int;
-> if new.col>30 then
-> insert into xxxx values (1);
-> end if;
-> end;
-> //
query ok, 0 rows affected (0.06 sec)
mysql> delimiter ;
mysql> delete from t_bluerosehero;
query ok, 3 rows affected (0.05 sec)
mysql> insert into t_bluerosehero values (1,20);
query ok, 1 row affected (0.06 sec)
mysql> insert into t_bluerosehero values (2,40);
error 1146 (42s02): table 'csdn.xxxx' doesn't exist
mysql>