while loop inside a trigger to loop through all the columns of table in sql

后端 未结 2 1303
有刺的猬
有刺的猬 2020-12-31 17:35

I have a trigger like below on user table to insert into the audit table with which column was updated and previous value:

ALTER TRIGGER [dbo].[trgAfterUpdat         


        
2条回答
  •  迷失自我
    2020-12-31 18:27

    Try this one -

    ALTER TRIGGER [dbo].[trgAfterUpdate] 
    
        ON [dbo].[tbl_User]
        AFTER UPDATE
    
    AS BEGIN
    
        SET NOCOUNT ON
        SET XACT_ABORT ON
    
        DECLARE @DocumentUID UNIQUEIDENTIFIER
    
        DECLARE cur CURSOR FORWARD_ONLY READ_ONLY LOCAL FOR
            SELECT DocumentUID, ...
            FROM INSERTED
    
        OPEN cur
    
        FETCH NEXT FROM cur INTO @DocumentUID, ...
    
        WHILE @@FETCH_STATUS = 0 BEGIN
    
            DECLARE 
                  @BeforeChange XML 
                , @AfterChange XML
    
            SELECT @BeforeChange = (
                SELECT *
                FROM DELETED
                WHERE [DocumentUID] = @DocumentUID
                FOR XML RAW, ROOT
            )
            , @AfterChange = (
                SELECT *
                FROM INSERTED
                WHERE [DocumentUID] = @DocumentUID
                FOR XML RAW, ROOT
            )
    
            INSERT INTO dbo.LogUser (DocumentUID, BeforeChange, AfterChange)
            SELECT @DocumentUID, @BeforeChange, @AfterChange
    
            -- your business logic 
    
            FETCH NEXT FROM cur INTO @DocumentUID, ...
    
        END
    
        CLOSE cur
        DEALLOCATE cur
    
    END
    

提交回复
热议问题