MySQL中建立一个update触发器,如果某字段变为0则删去该行 20
假设有个表tCREATETABLEt(idINT,countINT);我希望建立一个触发器,当表t被更新时,如果字段count被设置为0,则删去该行该如何做?...
假设有个表t
CREATE TABLE t (id INT, count INT);
我希望建立一个触发器,当表t被更新时,如果字段count被设置为0,则删去该行
该如何做? 展开
CREATE TABLE t (id INT, count INT);
我希望建立一个触发器,当表t被更新时,如果字段count被设置为0,则删去该行
该如何做? 展开
4个回答
展开全部
mysql> CREATE TABLE t (id INT, count INT);
Query OK, 0 rows affected (0.05 sec)
mysql> DELIMITER //
mysql> CREATE TRIGGER BeforeUpdateT
-> AFTER UPDATE ON t
-> FOR EACH ROW
-> BEGIN
-> IF new.count = 0 THEN
-> DELETE FROM t WHERE id = new.id;
-> END IF;
-> END;
-> //
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO t VALUES(1, 100) //
Query OK, 1 row affected (0.01 sec)
mysql> UPDATE t SET `count` = 0 //
ERROR 1442 (HY000): Can't update table 't' in stored function/trigger because it
is already used by statement which invoked this stored function/trigger.
建了一个,结果失败了。
原因是 MySQL 触发器里面,不让你更新被触发的表。
Query OK, 0 rows affected (0.05 sec)
mysql> DELIMITER //
mysql> CREATE TRIGGER BeforeUpdateT
-> AFTER UPDATE ON t
-> FOR EACH ROW
-> BEGIN
-> IF new.count = 0 THEN
-> DELETE FROM t WHERE id = new.id;
-> END IF;
-> END;
-> //
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO t VALUES(1, 100) //
Query OK, 1 row affected (0.01 sec)
mysql> UPDATE t SET `count` = 0 //
ERROR 1442 (HY000): Can't update table 't' in stored function/trigger because it
is already used by statement which invoked this stored function/trigger.
建了一个,结果失败了。
原因是 MySQL 触发器里面,不让你更新被触发的表。
追问
对的,我就是不知道怎么解决这个问题
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
mysql> delimiter //
mysql> CREATE TRIGGER t_trigger AFTER UPDATE ON t
-> FOR EACH ROW
-> BEGIN
-> DELETE FROM t WHERE count=0 AND id =NEW.id;
-> END;//
mysql> delimiter ;
希望能帮到你
mysql> CREATE TRIGGER t_trigger AFTER UPDATE ON t
-> FOR EACH ROW
-> BEGIN
-> DELETE FROM t WHERE count=0 AND id =NEW.id;
-> END;//
mysql> delimiter ;
希望能帮到你
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
create trigger deletecount
on t for insert, update
as begin
delete t from t,deleted
where t.[id]=deleted.[id] and t.count=0
end
on t for insert, update
as begin
delete t from t,deleted
where t.[id]=deleted.[id] and t.count=0
end
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
使用更新前触发器:
create trigger Mytrg
on 表t
instead of update
as
declare @count int,@id int
begin
select @id=id,@count=count from inserted
if(@count <>0)
update 表t set count=@count where id=@id
else
delete from 表t where id=@id
end
create trigger Mytrg
on 表t
instead of update
as
declare @count int,@id int
begin
select @id=id,@count=count from inserted
if(@count <>0)
update 表t set count=@count where id=@id
else
delete from 表t where id=@id
end
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询