日期:2014-05-17  浏览次数:20870 次

触发器如何批量更新?

/*
表1:T_Test

编号 类型
1 A
2 A
3 A
4 B
5 B
6 B

表2:T_Student

编号 姓名
1 小明
2 小强
3 小军
4 小红
5 小玲
6 小巧

两个表的编号都为主键唯一的,
写一个更新触发器在T_Test上,当T_Test的编号更新时,T_Student表的编号跟着其更新
批量更新时这个触发器怎么写?(如执行:update T_Test set 编号='00'+编号 where 类型='A')

*/

----建立测试环境(MSSQL2008)
if  exists (select * from sysobjects where id = object_id(N'[T_Test]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  drop table [T_Test]
GO
CREATE TABLE [dbo].[T_Test](
[编号] [varchar](50) NOT NULL,
[类型] [varchar](50) NULL,
 CONSTRAINT [PK_T_Test] PRIMARY KEY CLUSTERED 
(
[编号] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
insert into T_Test(编号,类型) select '1','A'
insert into T_Test(编号,类型) select '2','A'
insert into T_Test(编号,类型) select '3','A'
insert into T_Test(编号,类型) select '4','B'
insert into T_Test(编号,类型) select '5','B'
insert into T_Test(编号,类型) select '6','B'

go

if  exists (select * from sysobjects where id = object_id(N'[T_Student]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  drop table [T_Student]
GO

CREATE TABLE [dbo].[T_Student](
[编号] [varchar](50) NOT NULL,
[姓名] [varchar](50) NULL,
 CONSTRAINT [PK_T_Student] PRIMARY KEY CLUSTERED 
(
[编号] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
insert into T_Student(编号,姓名) select '1','小明'
insert into T_Student(编号,姓名) select '2','小强'
insert into T_Student(编号,姓名) select '3','小军'
insert into T_Student(编号,姓名) select '4','小红'
insert into T_Student(编号,姓名) select '5','小玲'
insert into T_Student(编号,姓名) select '6','小巧'

GO


----创建TR_Update_T_Student的更新触发器,这个触发器只能一条更新时有效
if(exists (select * from sysobjects where id=object_id(N'[TR_Update_T_Student]') and objectproperty(id,N'IsTrigger')=1))
drop TRIGGER [TR_Update_T_Student]
GO
CREATE TRIGGER [TR_Update_T_Student] ON [dbo].[T_Test]   
FOR UPDATE  
AS  
Begin Transaction
    UPDATE T_student SET T_student.编号=(SELECT top 1 编号 FROM inserted)  
    WHERE T_student.编号 in (SELECT  编号 FROM Deleted)  
Commit Transaction
go
select * from T_Test
select * from T_Student


go
-- update T_Test set 编号='00'+编号 where 类型='A' --执行无效
--T_Student表不能跟着T_tes