触发器在过去的10年中,即存储过程和ado.net称霸江湖期间是那么的重要,而现在,trigger显得不是那么必要的,我们很少将复杂的业务写在SQL里,当然也会没有机会写到trigger里了,可对于数据库本身来说,这东西还是要说说的,尤其是一些特殊场合,看看下面的触发器使用场合:
这种结构很有意思,在SQLSERVER中实现两个数据库实时同步的方法有很多,比较简单的是“发布与订阅”,但说实话,这东西是有风显的,只要一个服务重新启动,它的同步数据就被删除了,即,后台数据库数据被删除,需要重新进行同步,感觉挺危险的,今天主要说的是一种传统的方法实现某些表数据的同步,即使用触发器实现数据的同步。
我们以Category表为例,前台数据库名为[background],后台数据库名为[background_copy],当category表有数据插入时,[background_copy]表的数据自动实现插入,看一下代码部分吧:
USE [background] GO /****** Object: Trigger [dbo].[Trigger_Categoryinsert] Script Date: 09/10/2013 15:31:41 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dbo].[Trigger_Categoryinsert] ON [background].[dbo].[Category] AFTER INSERT AS SET IDENTITY_INSERT background_copy.[dbo].[Category] ON INSERT INTO background_copy.dbo.category ( [ID] , [ParentID] , [Level] , [Name] , [IsParent] , [CreateDate] , [Sortable] ) SELECT [ID] , [ParentID] , [Level] , [Name] , [IsParent] , [CreateDate] , [Sortable] FROM INSERTED SET IDENTITY_INSERT background_copy.[dbo].[Category] OFF
我们可以看到,代码中使用SET IDENTITY_INSERT TableName ON/OFF命令,即,你的数据表主键是自增的,在同步时,需要去掉后台表的自增特性,这样才可以与前台的自增主键保持一致。
下面再看一下触发器的更新,使用场合介绍:当category表的name字段有更新后,自动同步到background_copy.[dbo].[Category] 表的name字段
USE [background] GO /****** Object: Trigger [dbo].[Trigger_CategoryUpdate] Script Date: 09/10/2013 16:06:31 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dbo].[Trigger_CategoryUpdate] ON [dbo].[Category] AFTER UPDATE AS IF UPDATE(Name) BEGIN UPDATE [background_copy].[dbo].[Category] SET [Name] = ( SELECT name FROM INSERTED ) WHERE ID = ( SELECT id FROM INSERTED ) END
再来看一个更新表所有字段的,事实上就是把原来的记录删除,把新修改的记录插入就可以了,要求你注意的是自增主键的开关问题,看代码:
USE [BACKGROUND_COPY] GO /****** OBJECT: TRIGGER [DBO].[TRIGGER_CATEGORYUPDATE] SCRIPT DATE: 09/13/2013 18:01:00 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [DBO].[TRIGGER_CATEGORYUPDATE] ON [DBO].[CATEGORY] AFTER UPDATE AS DELETE BACKGROUND_COPY2.DBO.CATEGORY WHERE ID = ( SELECT ID FROM INSERTED ) SET IDENTITY_INSERT BACKGROUND_COPY2.DBO.CATEGORY ON INSERT INTO BACKGROUND_COPY2.DBO.CATEGORY ( ID , PARENTID , LEVEL , NAME , ISPARENT , CREATEDATE , SORTABLE ) SELECT * FROM INSERTED SET IDENTITY_INSERT BACKGROUND_COPY2.DBO.CATEGORY OFF
看一下删除功能的触发器:
USE [BACKGROUND_COPY] GO /****** OBJECT: TRIGGER [DBO].[TRIGGER_CATEGORYDELETE] SCRIPT DATE: 09/13/2013 17:58:27 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [DBO].[TRIGGER_CATEGORYDELETE] ON [DBO].[CATEGORY] AFTER DELETE AS DELETE BACKGROUND_COPY2.DBO.CATEGORY WHERE ID = ( SELECT ID FROM DELETED )
OK,现在我们的category表就可以实现自动同步了,呵呵
本文转自博客园张占岭(仓储大叔)的博客,原文链接:知方可补不足~sqlserver中触发器的使用,如需转载请自行联系原博主。