VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 数据库 > sql数据库 >
  • sql语句大全之触发器捕获批量修改

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

复制代码
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
复制代码

 


相关教程