------------------------------------ -- Author: happyflystone -- Version:V1.001 -- Date:2008-09-15 11:01:10 -------------------------------------- Test Data: ta If object_id('ta') is not null Drop table ta Go Create table ta(id int,dpr nvarchar(4)) Go Insert into ta select 1,'人力资源' union all select 2,'财务' Go -- Test Data: tb If object_id('tb') is not null Drop table tb Go Create table tb(id int,worker_name nvarchar(2),dpr nvarchar(4)) Go Insert into tb select 1,'张三','人力资源' Go --Start create trigger tr_up on ta for update as begin update tb set Dpr=b.Dpr from tb a,inserted b,deleted d where d.id=b.id and a.dpr = d.dprend go update ta set dpr = '工程部' where id = 1 select * from tb--Result: /*id worker_name dpr ----------- ----------- ---- 1 张三 工程部(所影响的行数为 1 行)*/ --End
创建一个Update触发器:Create Trigger T1 On 表1 for Update As if Update(dpr) beginUpdate 表2 Set drp=i.drp From 表2 tab2 , Deleted d ,Inserted i Where tab2.StudentID=d.StudentIDend 理解触发器里面的两个临时的表:Deleted , Inserted 。注意Deleted 与Inserted分别表示触发事件的表“旧的一条记录”和“新的一条记录”。 一个Update 的过程可以看作为:生成新的记录到Inserted表,复制旧的记录到Deleted表,然后删除表1记录并写入新纪录。
-- Author: happyflystone
-- Version:V1.001
-- Date:2008-09-15 11:01:10
-------------------------------------- Test Data: ta
If object_id('ta') is not null
Drop table ta
Go
Create table ta(id int,dpr nvarchar(4))
Go
Insert into ta
select 1,'人力资源' union all
select 2,'财务'
Go
-- Test Data: tb
If object_id('tb') is not null
Drop table tb
Go
Create table tb(id int,worker_name nvarchar(2),dpr nvarchar(4))
Go
Insert into tb
select 1,'张三','人力资源'
Go
--Start
create trigger tr_up
on ta
for update
as
begin
update tb
set Dpr=b.Dpr
from tb a,inserted b,deleted d
where d.id=b.id and a.dpr = d.dprend
go
update ta set dpr = '工程部' where id = 1
select * from tb--Result:
/*id worker_name dpr
----------- ----------- ----
1 张三 工程部(所影响的行数为 1 行)*/
--End
On 表1
for Update
As
if Update(dpr)
beginUpdate 表2
Set drp=i.drp
From 表2 tab2 , Deleted d ,Inserted i
Where tab2.StudentID=d.StudentIDend 理解触发器里面的两个临时的表:Deleted , Inserted 。注意Deleted 与Inserted分别表示触发事件的表“旧的一条记录”和“新的一条记录”。
一个Update 的过程可以看作为:生成新的记录到Inserted表,复制旧的记录到Deleted表,然后删除表1记录并写入新纪录。
当然,若表结构不能动,也可以用主外键的级联更新,不过此时应该把第一张表的 dpr 设为主键。