Solution for Can’t update table ‘t1′ in stored function/trigger because it is already used by statement which invoked this store

In recently project, i needed to fix a bug about database update. The best way to solve this problem is create an update trigger, but when finished this trigger desiger, a problem show up which the error description is "Can’t update table ‘t1′ in stored function/trigger because it is already used by statement which invoked this stored function/trigger.". So after searched the answer from website, i got a solution about this issue.The following is a sample to show how to fix this problem.

This is a sample table:


CREATE TABLE `t1`

( `a` char(1) default NULL, `b` smallint(6) default NULL );

insert into t1 values ('y','1');

I have a table t1 which has column a and b, i want column a to be updated "n" when column b=0.Here is the fist version i created:


DELIMITER |

CREATE TRIGGER trigger1 AFTER UPDATE ON t1 FOR EACH ROW UPDATE t1 SET a= 'n' WHERE b=0;

| DELIMITER ;

After executed this trigger succesfully, i got an error when i start to update this table.The error statement is "Can't update table 't1' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.".

The following trigger code is a good way:


drop trigger trigger1;

DELIMITER |

CREATE TRIGGER trigger1

BEFORE UPDATE ON t1

FOR EACH ROW

BEGIN IF NEW.b=0 THEN SET NEW.a = 'n';

END IF; END

| DELIMITER ;

Now you can update the table t1. After got this solution i use it on my project.This is the update trigger i wrote:

DELIMITER $$

DROP TRIGGER ModifyLastUpdated

create trigger ModifyLastUpdated BEFORE UPDATE on EMPLOYEE_SKILL for each row

BEGIN if

old.eid=new.eid and old.skill_id=new.skill_id

then set new.last_updated=current_timestamp;

end if;

END;

$$ DELIMITER ;

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值