zoukankan      html  css  js  c++  java
  • 触发器捕获批量修改

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

    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
  • 相关阅读:
    php $_SERVER中的SERVER_NAME 和HTTP_HOST的区别
    手机web——自适应网页设计(html/css控制)
    js正则表达式语法
    禁止鼠标右键的代码(转)
    php获取文件名称和扩展名
    php中奖概率算法,可用于刮刮卡,大转盘等抽奖算法
    js中cookie的使用详细分析
    fopen中r+和w+的区别
    左右选择框 js插件
    SpringMVC 过滤器Filter使用解析
  • 原文地址:https://www.cnblogs.com/xietong/p/6237288.html
Copyright © 2011-2022 走看看