Audit
我有一个触发器,可以在更新某些列时记录到表中。删除一列后我在使用时遇到了很多问题columns_updated()
,所以我重写了仅使用的触发器Update()
,这似乎有效。
IF
但是,我在每个语句中不断重复查询If Update(ColumnName)
,请参见下面的代码,因为我需要动态更改列名。有没有办法欺骗这个,所以我不必不断重复INSERT
查询?
IF (@TYPE IN ('U') and UPDATE(ShippingAddressFlag))
BEGIN
SELECT @fieldname = 'ShippingAddressFlag'
SELECT @SQL = 'insert Audit (Type, TableName, PKCol, PK, FieldName, OldValue, NewValue, UpdateDate, DBUserName, UserID)'
SELECT @SQL = @SQL + ' select ''' + @TYPE + ''''
SELECT @SQL = @SQL + ',''' + @TableName + ''''
SELECT @SQL = @SQL + ',''' + @PKCol + ''''
SELECT @SQL = @SQL + ',' + @PK
SELECT @SQL = @SQL + ',''' + @fieldname + ''''
SELECT @SQL = @SQL + ',convert(varchar(1000),d.' + replace(@fieldname, '''', '') + ')'
SELECT @SQL = @SQL + ',convert(varchar(1000),i.' + replace(@fieldname, '''', '') + ')'
SELECT @SQL = @SQL + ',''' + @UpdateDate + ''''
SELECT @SQL = @SQL + ',''' + @UserName + ''''
SELECT @SQL = @SQL + ',''' + @UserID + ''''
SELECT @SQL = @SQL + ' from #ins i full outer join #del d'
SELECT @SQL = @SQL + @PKCols
SELECT @SQL = @SQL + ' where i.' + @fieldname + ' <> d.' + @fieldname
SELECT @SQL = @SQL + ' or (i.' + @fieldname + ' is null and d.' + @fieldname + ' is not null)'
SELECT @SQL = @SQL + ' or (i.' + @fieldname + ' is not null and d.' + @fieldname + ' is null)'
Print @SQL
END
IF (@TYPE IN ('U') and UPDATE(Amount))
BEGIN
SELECT @fieldname = 'Amount'
SELECT @SQL = 'insert Audit (Type, TableName, PKCol, PK, FieldName, OldValue, NewValue, UpdateDate, DBUserName, UserID)'
SELECT @SQL = @SQL + ' select ''' + @TYPE + ''''
SELECT @SQL = @SQL + ',''' + @TableName + ''''
SELECT @SQL = @SQL + ',''' + @PKCol + ''''
SELECT @SQL = @SQL + ',' + @PK
SELECT @SQL = @SQL + ',''' + @fieldname + ''''
SELECT @SQL = @SQL + ',convert(varchar(1000),d.' + replace(@fieldname, '''', '') + ')'
SELECT @SQL = @SQL + ',convert(varchar(1000),i.' + replace(@fieldname, '''', '') + ')'
SELECT @SQL = @SQL + ',''' + @UpdateDate + ''''
SELECT @SQL = @SQL + ',''' + @UserName + ''''
SELECT @SQL = @SQL + ',''' + @UserID + ''''
SELECT @SQL = @SQL + ' from #ins i full outer join #del d'
SELECT @SQL = @SQL + @PKCols
SELECT @SQL = @SQL + ' where i.' + @fieldname + ' <> d.' + @fieldname
SELECT @SQL = @SQL + ' or (i.' + @fieldname + ' is null and d.' + @fieldname + ' is not null)'
SELECT @SQL = @SQL + ' or (i.' + @fieldname + ' is not null and d.' + @fieldname + ' is null)'
Print @SQL
END