Mysql 触发器(实际业务场景写法)
话不多说,直接进入整体
-- 查看当前库是否有改触发器,有则删除
DROP TRIGGER IF EXISTS zyttbi.apply_change_update;
create trigger apply_change_update
-- before和after update/inster/delete
before update on sg_apply_change
for each row
begin
-- 判断修改的状态的后八位是否等于11451002,也可以 = old.state 代表修改前的状态 then是返回值,条件成立
if right(new.state, 8) = '11451002' then
-- case 和后端代码同理
case right(new.applyType, 8)
when '11441000' then
update sg_apply t set t.buildStartTime= NOW(),t.state = concat(left(new.state, 4),'11421003') where t.id = new.applyID;
when '11441001' then
update sg_apply t set t.buildEndTime= NOW(),t.state = concat(left(new.state, 4),'11421003') where t.id = new.applyID;
end case;
end if;
end;
触发器写法必须有头有尾,希望大家注意 if - end if; case - end case;
至此一个简单业务场景的触发器就写完了,有问题欢迎评论提出