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

后端 未结 2 1304
有刺的猬
有刺的猬 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:21

    Try using query similar to this one – it will generate If statements for all columns of a given table.

    Note: This is not fully tested and probably needs more adjustments but you see the idea behind it.

    select 'if update(' + C.name + ')
      begin
          select @OldValue=j.' + C.name + ' from deleted j;  
          set @fieldname = ''' + C.name + ''';
    
            insert into tbl_Audit(user_key, field_name, previuos_Value, user_name)
            values(@User_Key ,@fieldname,@OldValue, @CreateUser);
      end'
    from sys.all_columns C
    inner join sys.tables T on C.object_id = T.object_id
    where T.name = 'table_name' and T.schema_id = SCHEMA_ID('schema_name')
    

    If wouldn’t go with while loop because it can probably cause perf issues…

提交回复
热议问题