首页 > 代码库 > 触发器捕获批量修改
触发器捕获批量修改
最近在批量更新数据时,发现无论怎么操作触发器都仅仅捕获到了一条数据,触发器代码大致如下。
ALTER TRIGGER [dbo].[Trigger_Demo_Update] ON [dbo].[B_Demo_TB] AFTER UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @NewData INT,@OldData INT; SELECT @OldData=Data FROM DELETED SELECT @NewData=Data FROM INSERTED IF(@OldData!=@NewData) BEGIN INSERT INTO M_TriggleSoft(Data) VALUES(@NewData) END END
我们知道在触发器中DELETE和INSERTED其实是两张虚表,因此用变量获取仅能得到一条数据,但是如果用游标的话可以获取到位于虚表中的所有数据,批量处理。于是修改如下:
ALTER TRIGGER [dbo].[Trigger_Demo_Update] ON [dbo].[B_Demo_TB] AFTER UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @NewData INT,@OldData INT; DECLARE cursorDel CURSOR FOR SELECT Data FROM DELETED DECLARE cursorINSERT CURSOR FOR SELECT Data FROM INSERTED open cursorDel open cursorINSERT FETCH NEXT FROM cursorDel INTO @OldData FETCH NEXT FROM cursorINSERT INTO @NewData WHILE @@FETCH_STATUS=0 BEGIN IF(@OldData!=@NewData) BEGIN INSERT INTO M_TriggleSoft(Data) VALUES(@NewData) END FETCH NEXT FROM cursorDel INTO @OldData FETCH NEXT FROM cursorINSERT INTO @NewData END CLOSE cursorDel DEALLOCATE cursorDel CLOSE cursorINSERT DEALLOCATE cursorINSERT END
既然明白了触发器中DELETE和INSERTED是两张虚表,那么其实上述的操作也可以这么来:
ALTER TRIGGER [dbo].[Trigger_Demo_Update] ON [dbo].[B_Demo_TB] AFTER UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @NewData INT,@OldData INT; SELECT @OldData=Data FROM DELETED SELECT @NewData=Data FROM INSERTED INSERT INTO M_TriggleSoft(DATA) SELECT Data FROM INSERTED INNER JOIN DELETED ON INSERTED.ID=DELETED.ID WHERE INSERTED.DATA=DELETED.DATA END END
触发器捕获批量修改
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。