在日常工作中,在SqlServer2008R2中,需要向一張表上加上觸發器,監控插入、更新、刪除。 下麵是我這寫的語句,供網友借鑒、參考: ...
在日常工作中,在SqlServer2008R2中,需要向一張表上加上觸發器,監控插入、更新、刪除。
--一個觸發器內三種INSERT,UPDATE,DELETE狀態 IF exists(select 1 from inserted) and not exists(select 1 from deleted) begin --INSERT end IF exists(select 1 from inserted) and exists(select 1 from deleted) begin --UPDATE end IF exists(select 1 from deleted) and not exists(select 1 from inserted) begin --DELETE end --插入操作(Insert):Inserted表有數據,Deleted表無數據 --刪除操作(Delete):Inserted表無數據,Deleted表有數據 --更新操作(Update):Inserted表有數據(新數據),Deleted表有數據(舊數據)
下麵是我這寫的語句,供網友借鑒、參考:
CREATE trigger [dbo].[deal_Trace_globe_Data] on [dbo].[DirectPriceZoneAndBunding] for insert,update,delete as begin --插入或更新 IF exists(select 1 from inserted) begin DECLARE @ID nvarchar(50) DECLARE @CustCode nvarchar(8) DECLARE @Version int DECLARE @OperateTime datetime DECLARE c1 CURSOR for SELECT [ID],[CustCode],[Version],[OperateTime] from inserted OPEN c1 FETCH NEXT FROM c1 into @ID,@CustCode,@Version,@OperateTime WHILE @@FETCH_STATUS=0 BEGIN DECLARE @Count int DECLARE @No_Count int --插入 if not exists(select 1 from deleted) begin SELECT @Count = count(1) FROM trace_globe.dbo.DirectPriceZoneAndBunding WHERE ID = (select ID from inserted) SELECT @No_Count = COUNT(1) FROM inserted IF @Count <=0 and @No_Count>0 begin insert into trace_globe.dbo.DirectPriceZoneAndBunding([ID],[CustCode],[Version],[OperateTime]) select [ID],[CustCode],[Version],[OperateTime] from inserted where ID=@ID end end else --更新 begin SELECT @Count = count(1) FROM trace_globe.dbo.DirectPriceZoneAndBunding WHERE ID = (select ID from deleted) SELECT @No_Count = COUNT(1) FROM deleted IF @Count >0 and @No_Count>0 begin update trace_globe.dbo.DirectPriceZoneAndBunding set [ID]=@ID,[CustCode]=@CustCode,[Version]=@Version,[OperateTime]=@OperateTime where [ID]=@ID end end FETCH NEXT FROM c1 into @ID,@CustCode,@Version,@OperateTime END CLOSE c1 DEALLOCATE c1 end --刪除 IF exists(select 1 from deleted) and not exists(select 1 from inserted) begin DECLARE @deleteID nvarchar(50) DECLARE c2 CURSOR for SELECT [ID] from deleted OPEN c2 FETCH NEXT FROM c2 into @deleteID WHILE @@FETCH_STATUS=0 BEGIN delete from trace_globe.dbo.DirectPriceZoneAndBunding where ID=@deleteID FETCH NEXT FROM c2 into @deleteID END CLOSE c2 DEALLOCATE c2 end end