在sqlserver2008中因为服务器网络设置须要,部署了两个结构相同的数据库,并要求对这两个数据库中其中任何一个库作任何更改均要同步到另外一个库中sql
因此就在两个库分别建立了触发器,以便同步数据库
------------------------------------------------------------------------------服务器
如库1为hmi_Yanke,库2为hmi_Yanke2,两个库都存在表TDisplay网络
则在库1建立触发器以下sqlserver
1 --建立[hmi_Yanke].[dbo].[TDisplay]表的触发器 2 create trigger [dbo].[trigger_TDisplay] 3 on [HMI_YanKe2].[dbo].[TDisplay] 4 AFTER INSERT,UPDATE,DELETE 5 as 6 begin 7 declare @RowsD Int,@RowsI Int,@Dml Int 8 --肯定是哪种dml操做 9 Select @RowsD=Count(*) From Deleted 10 Select @RowsI=Count(*) From Inserted 11 If @RowsD=0 And @RowsI=0 12 Goto Exit_ 13 If @RowsD=0 And @RowsI>0 14 Set @Dml=1 15 Else If @RowsD>0 And @RowsI>0 16 Set @Dml=2 17 Else If @RowsD>0 And @RowsI=0 18 Set @Dml=3 19 IF @DML=1 20 BEGIN 21 --插入 22 IF NOT EXISTS(SELECT TOP 1 1 FROM [hmi_Yanke].[dbo].[TDisplay] c,inserted i where c.FID=i.FID) 23 begin 24 set IDENTITY_INSERT [hmi_Yanke].[dbo].[TDisplay] ON 25 insert into [hmi_Yanke].[dbo].[TDisplay]( [FID],FFieldCN,FFieldEN,FTable,FOrder,FType,FNullable,FLength,FWidth) 26 select [FID],FFieldCN,FFieldEN,FTable,FOrder,[FType],FNullable,FLength,FWidth from inserted 27 set IDENTITY_INSERT [hmi_Yanke].[dbo].[TDisplay] OFF 28 end 29 END 30 IF @DML=2 31 begin 32 --修改 33 IF NOT EXISTS 34 (SELECT TOP 1 1 FROM [hmi_Yanke].[dbo].[TDisplay] c,INSERTED i 35 where c.[FID]=i.[FID] and c.FFieldCN=i.FFieldCN and c.FFieldEN=i.FFieldEN and c.FTable=i.FTable 36 and c.FOrder=i.FOrder and c.[FType]=i.[FType] and c.FNullable=i.FNullable and c.FLength=i.FLength 37 and c.FWidth=i.FWidth ) 38 UPDATE [hmi_Yanke].[dbo].[TDisplay] set FFieldCN=i.FFieldCN,FFieldEN=i.FFieldEN,FTable=i.FTable,FOrder=i.FOrder,[FType]=i.[FType],FNullable=i.FNullable,FLength=i.FLength,FWidth=i.FWidth 39 FROM [hmi_Yanke].[dbo].[TDisplay] c,INSERTED i where c.[FID]=i.[FID] 40 --select * from INSERTED 41 --select * from deleted 42 end 43 IF @DML=3 44 BEGIN 45 --删除 46 IF EXISTS(SELECT TOP 1 1 FROM [hmi_Yanke].[dbo].[TDisplay] c,deleted d where c.[FID]=d.[FID]) 47 DELETE [hmi_Yanke].[dbo].[TDisplay] FROM [hmi_Yanke].[dbo].[TDisplay] c,deleted d 48 WHERE c.[FID]=d.[FID] 49 END 50 EXIT_: 51 end
在库2建立触发器与上面相同,只须要将hmi_Yanke改成hmi_Yanke2便可测试
简单测试后获得正确结果spa
1 INSERT INTO [HMI_YanKe].[dbo].[TDisplay] values('haha','haha','haha',1,'haha',1,1,1),('hehe','hehe','hehe',2,'hehe',2,2,2) 2 INSERT INTO [HMI_YanKe2].[dbo].[TDisplay] values('xixi','xixi','xixi',1,'xixi',1,1,1),('keng','keng','keng',2,'keng',2,2,2) 3 4 update [HMI_YanKe].[dbo].[TDisplay] set FFieldCN='vinjack' where FFieldCN='haha' 5 update [HMI_YanKe2].[dbo].[TDisplay] set FFieldCN='vinjane' where FFieldCN='xixi' 6 7 delete [HMI_YanKe].[dbo].[TDisplay] where FFieldCN in('vinjack','hehe') 8 delete [HMI_YanKe2].[dbo].[TDisplay] where FFieldCN in('vinjane','keng') 9 10 select * FROM [HMI_YanKe].[dbo].[TDisplay] 11 select * FROM [HMI_YanKe2].[dbo].[TDisplay]