mysql 触发器 禁止插入_MySQL触发器在某些条件下阻止INSERT

782a832e5c29cf8c08e0a35f2a095e3c.png

饮歌长啸

示例1,MySQL,您可以在触发器中取消该插入 signal sqlstate使用varchar列创建表:mysql> create table yar (val VARCHAR(25) not null);Query OK, 0 rows affected (0.02 sec)创建'before insert'触发器以检查条件并禁用。mysql> delimiter $$mysql> create trigger foo before insert on yar    -> for each row    -> begin    -> if new.val = '' then    -> signal sqlstate '45000';    -> end if;    -> end;$$Query OK, 0 rows affected (0.01 sec)尝试插入满足条件的位置:mysql> delimiter ;mysql> insert into yar values("");ERROR 1644 (45000): Unhandled user-defined exception conditionmysql> insert into yar values ("abc");Query OK, 1 row affected (0.01 sec)mysql> select * from yar;+-----+| val |+-----+| abc |+-----+1 row in set (0.00 sec)你插入一个空白字符串,触发器看到它是空白的,并提出信号,以防止插入。示例2,MySQL,通过使数据违反非空约束来取消触发器中的插入。使用varchar列创建表:mysql> create table yar (val VARCHAR(25) not null);Query OK, 0 rows affected (0.02 sec)创建'before insert'触发器以检查条件并禁用。mysql> delimiter $$mysql> create trigger foo before insert on yar    -> for each row    -> begin    -> if new.val = '' then    -> set new.val = NULL;    -> end if;    -> end;$$Query OK, 0 rows affected (0.01 sec)尝试插入满足条件的位置:mysql> delimiter ;mysql> insert into yar values("");ERROR 1048 (23000): Column 'val' cannot be nullmysql> insert into yar values ("abc");Query OK, 1 row affected (0.01 sec)mysql> select * from yar;+-----+| val |+-----+| abc |+-----+1 row in set (0.00 sec)您插入了一个空白字符串,触发器看到它是空白的并将值更改为null,因此阻止插入。

你可能感兴趣的:(mysql,触发器,禁止插入)