MySQL5.6 触发器的使用(条件分支、变量的使用)

来源:互联网 发布:windows repair win10 编辑:程序博客网 时间:2024/04/30 20:47
create trigger check_record_delete_trigger after DELETEon check_record FOR EACH ROWbeginset @count = (select count(*) from check_record where INSTRUMENT_ID = old.INSTRUMENT_ID);if @count = 0 thenset @Ins = 'drop Instrument';delete from product_info where product_id = old.INSTRUMENT_ID and product_flag = 0;elseif @count > 0 THENset @Ins = 'Keep it';end if;set @count = (select count(*) from check_record where REAGENT_ID = old.REAGENT_ID);if @count = 0 thenset @Rea = 'drop Reagent';delete from product_info where product_id = old.REAGENT_ID and product_flag = 1;elseif @count > 0 THENset @Rea = 'Keep it';end if;end;

这段代码的意思是,删除主表 check_record中的一条记录时,也要相应地删除product_info表中相关联的记录,用instrument_id和reagent_id关联。

因为product_info表中的prouct_id在check_record中体现为instrument_id和reagent_id两个字段(product_info表中包括两种记录:instrument和reagent),

并且在check_record中会有多条记录有相同的instrument_id和reagent_id,所以每次删除时要进行判断,如果check_record中还有instrument_id或者reagent_id存在,那么

procut_info中就不能删,反之如果check_record中已经没有了特定值的instrument_id和reagent_id,那么product_info中的对应记录也就失去了存在的意义,所以要删除。


有几个注意点:

1. 关于if else分支在mysql中的使用,只能出现在存储过程、函数或者触发器中,如果在控制台中普通的查询语句中出现if else是会报语法错误的。

2. 有if, 就必须有end if,不然就报语法错误,这一点和java、JS等语言不一样,并且,end if后面必须加分号,不然报错。

3. 关于给变量赋值,必须以 set...开头,set不能省略,否则报语法错误。

4. 关于”old“,它指的是刚被删除的那条记录,也就是说,这条记录中的字段值还是可以拿出来用一下的。


0 1
原创粉丝点击