USE [learn2] GO /****** Object: Trigger [dbo].[trigger_AdClass] Script Date: 09/30/2014 09:01:03 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,sushine> -- Create date: <Create Date,,2014-9-29> -- Description: <Description,,保证子父级 webpageId 关联一致;或者子级单独是可以的> -- ============================================= create TRIGGER [dbo].[trigger_AdClass] on [dbo].[AdClass] AFTER insert,update AS BEGIN try declare @err nvarchar(256),@classId int,@parentId int; if(exists(select 1 from inserted))--当增加一条数据的时候和当修改parentId的时候 begin select @classId=classId from inserted; select @parentId=parentId from inserted; if(@parentId is not null) begin update AdClass set WebPageId=(select WebPageId from AdClass where ClassId=@parentId) where AdClass.ClassId=@classId; end end if(update(webpageId))--当修改webpageId的时候 begin select @classId=classId from inserted; update AdClass set WebPageId=i.WebPageId from inserted i where adclass.ClassId in(select ClassId from dbo.AdClassTree(@classId,null) where Depth>1); end --else if(update(parentId)) --begin -- select @parentId= parentId from inserted; -- select @classId=classId from inserted; -- update AdClass set WebPageId=(select WebPageId from AdClass where ClassId=@parentId) where adclass.ClassId=@classId; --end end try begin catch rollback; set @err=ERROR_MESSAGE(); Raiserror(@err,16,0); end catch
触发器 inserted 和 deleted 两种。
当insert 和update的时候用inserted