SQL Server Update Trigger, Get Only modified fields

前端 未结 8 1226
旧巷少年郎
旧巷少年郎 2020-11-29 03:44

I am aware of COLUMNS_UPDATED, well I need some quick shortcut (if anyone has made, I am already making one, but if anyone can save my time, I will appriciate i

8条回答
  •  迷失自我
    2020-11-29 04:19

    The only way that occurs to me that you could accomplish this without hard coding column names would be to drop the contents of the deleted table to a temp table, then build a query based on the table definition to to compare the contents of your temp table and the actual table, and return a delimited column list based on whether they do or do not match. Admittedly, the below is elaborate.

    Declare @sql nvarchar(4000)
    DECLARE @ParmDefinition nvarchar(500)
    Declare @OutString varchar(8000)
    Declare @tbl sysname
    
    Set @OutString = ''
    Set @tbl = 'SomeTable' --The table we are interested in
    --Store the contents of deleted in temp table
    Select * into #tempDelete from deleted 
    --Build sql string based on definition 
    --of table 
    --to retrieve the column name
    --or empty string
    --based on comparison between
    --target table and temp table
    set @sql = ''
    Select @sql = @sql + 'Case when IsNull(i.[' + Column_Name + 
    '],0) = IsNull(d.[' + Column_name + '],0) then '''' 
     else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
    from information_schema.columns 
    where table_name = @tbl
    --Define output parameter
    set @ParmDefinition = '@OutString varchar(8000) OUTPUT'
    --Format sql
    set @sql = 'Select @OutString = ' 
    + Substring(@sql,1 , len(@sql) -1) + 
    ' From SomeTable i  ' --Will need to be updated for target schema
    + ' inner join #tempDelete d on
    i.PK = d.PK ' --Will need to be updated for target schema
    --Execute sql and retrieve desired column list in output parameter
    exec sp_executesql @sql, @ParmDefinition, @OutString OUT
    drop table  #tempDelete
    --strip trailing column if a non-zero length string 
    --was returned
    if Len(@Outstring) > 0 
        Set @OutString = Substring(@OutString, 1, Len(@Outstring) -1)
    --return comma delimited list of changed columns. 
    Select @OutString 
    End
    

提交回复
热议问题