34,594
社区成员
发帖
与我相关
我的任务
分享
我现在有个表A
id num1 num2 state
1 10 5 0
2 8 3 0
3 6 6 1
我想写一个修改的触发器
当去修改 num2 字段时,此时做个判断
判断修改后的 num2 是否等于 num1
如果相等就把对应的 state 改为 1
create trigger trigU_A on A
for update
as
update aa
set state=1
from a aa,inserted bb
where aa.id=bb.id and bb.num1=bb.num2
Create table [a]([id] int,[num1] int,[num2] int,[state] int)
Insert a
Select 1,10,5,0 union all
Select 2,8,3,0 union all
Select 3,6,6,1
Go
create trigger trigup on a
for update
as
begin
if update(num2)
begin
update a set state=1 FROM INSERTED I where A.id=I.ID AND A.NUM1=I.NUM2
end
end
Create table [a]([id] int,[num1] int,[num2] int,[state] int)
Insert a
Select 1,10,5,0 union all
Select 2,8,3,0 union all
Select 3,6,6,1
Go
create trigger trigup on a
for update
as
begin
if update(num2)
begin
update a set state=1 where id in (select id from inserted i where num1=num2)
end
end
-- =========================================
-- -----------t_mac 小编-------------
---希望有天成为大虾----
-- =========================================
IF OBJECT_ID('tb') IS NOT NULL
DROP TABLE tb
GO
CREATE TABLE tb(id int,num1 int,num2 int, state int)
go
insert tb SELECT
1 , 10 , 5 , 0UNION ALL SELECT
2 , 8 , 3 , 0UNION ALL SELECT
3 , 6 , 6 , 1
go
create trigger k on tb
after update
as
begin
if update(num2)
if exists(select * from inserted where num1=num2)
update tb
set state=1
from inserted i
where i.num2=tb.num2
end
update tb
set num2=10
where id=1
select * from tb
go
/*------------
id num1 num2 state
----------- ----------- ----------- -----------
1 10 10 1
2 8 3 0
3 6 6 1
(3 行受影响)
-------*/
---------------------------------
-- Author: htl258(Tony)
-- Date : 2009-07-30 18:55:49
---------------------------------
--> 生成测试数据表:a
If not object_id('[a]') is null
Drop table [a]
Go
Create table [a]([id] int,[num1] int,[num2] int,[state] int)
Insert a
Select 1,10,5,0 union all
Select 2,8,3,0 union all
Select 3,6,6,1
Go
--Select * from a
-->SQL查询如下:
--创建触发器
If not object_id('[tr_test]') is null
Drop trigger tr_test
Go
create trigger tr_test on a
for update
as
update a set
state = 1
from a
join inserted b
on a.id=b.id
and b.num2=b.num1
go
--测试
update a set a.num2=10 where id=1
select * from a
/*
id num1 num2 state
----------- ----------- ----------- -----------
1 10 10 1
2 8 3 0
3 6 6 1
(3 行受影响)
*/
create trigger k on tb
after uodate
as
begin
if exists(select * from inserted where num1=num2)
update tb
set state=1
from inserted i
where i.num2=num2
end
create trigger tr_test on a
for update
as
update a set
state = 1
from a
join inserted b
on a.id=b.id
where b.num2=b.num1
go