触发器捕获批量修改

Posted 大朋展翅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了触发器捕获批量修改相关的知识,希望对你有一定的参考价值。

  最近在批量更新数据时,发现无论怎么操作触发器都仅仅捕获到了一条数据,触发器代码大致如下。

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

 

以上是关于触发器捕获批量修改的主要内容,如果未能解决你的问题,请参考以下文章

Python调用Zabbix API接口批量修改(禁用/启用)触发器trigger

通过python封装zabbix-api批量修改模板中触发器名称

从片段中捕获图像

如何在片段中从相机捕获图像,

端午安康SXYPython正则表达式进阶用法(以批量修改Markdown英文字体为例)

端午安康SXYPython正则表达式进阶用法(以批量修改Markdown英文字体为例)