日期:2014-05-18  浏览次数:20445 次

一个触发器的问题
我想   写一个触发器     有   6个字段   控制   另一个字段   想实现   6个字段中的任何一个或者几个   值由1变成   0   另一个字段也跟着变化   请问怎么写   谢谢大家了

------解决方案--------------------
把tablename改成BM_xueyuan

create trigger tr_BM_xueyuan_update
on BM_xueyuan
for update
as

update a
Person_biye=0
from BM_xueyuan a,inserted i,deleted d
where a.Person_id=i.Person_id
and i.Person_id=d.Person_id
and (i.jiaojingkemuone=0 and d.jiaojingkemuone=1 or
i.jiaojingkemutwo=0 and d.jiaojingkemutwo=1 or
i.jiaojingkemutree=0 and d.jiaojingkemutree=1 or
i.jiaotongjuone=0 and d.jiaotongjuone=1 or
i.jiaotongjutwo=0 and d.jiaotongjutwo=1 or
i.jiashizheng=0 and d.jiashizheng=1 or
i.jieyezheng=0 and d.jieyezheng=1 )

------解决方案--------------------
触发器代码没问题,以下在我的机器上成功执行:
环境:windows2003 sp1 + SQLSERVER2000sp4

if object_id( 'tbTest ') is not null
drop table tbTest
GO
CREATE TABLE [dbo].[tbTest] (
[person_id] [int] NULL ,
[zhiwu_id] [int] NULL,
[Person_biye] [bit] NULL,
[jiaojingkemuone] [int] NULL,
[jiaojingkemutwo] [int] NULL
) ON [PRIMARY]
GO
insert tbTest
select 1,1,1,1,1 union all
select 2,1,1,1,1 union all
select 3,1,1,1,1 union all
select 4,1,1,1,1 union all
select 5,1,1,1,1
GO
create trigger tr_update_tbTest
on tbTest
for update
as
update a set Person_biye=0
from tbTest a,inserted i,deleted d
where a.Person_id=i.Person_id
and i.Person_id=d.Person_id
and (i.jiaojingkemuone=0 and d.jiaojingkemuone=1 or
i.jiaojingkemutwo=0 and d.jiaojingkemutwo=1)
GO

----更新
update tbTest set jiaojingkemuone = 0 where Person_id = 2

----查看
select * from tbTest

----清除测试环境
drop table tbTest

/*结果(person_id=2的Person_biye已经被成功更新为0)
person_id zhiwu_id Person_biye jiaojingkemuone jiaojingkemutwo
----------- ----------- ----------- --------------- ---------------
1 1 1 1 1
2 1 0 0 1
3 1 1 1 1
4 1 1 1 1
5 1 1 1 1
*/