我在 mssql 中有一个触发器,我想将插入表中的每一列与已删除表进行比较,以检查值是否已更改...如果值已更改,我想将列名插入临时表。
到目前为止我的代码:
declare columnCursor CURSOR FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTable' AND TABLE_SCHEMA='dbo'
--save inserted and deleted into temp tables
select * into #row1 from Inserted
select * into #row2 from Deleted
declare @tmp table(column_name nvarchar(max))
declare @column nvarchar(50)
OPEN COlumnCUrsor
FETCH NEXT FROM ColumnCursor INTO @column
while @@FETCH_STATUS=0 begin
declare @out bit
declare @sql nvarchar(max) = N'
select @out = case when r1.'+@column+'r2.'+@column+' then 1 else 0 end
from #row1 r1
left join #row2 r2 on r1.sys_volgnr=r2.sys_volgnr'
exec sp_executesql @sql,N'@out bit OUTPUT', @out=@out OUTPUT
if( @out = 1 ) begin
insert into @tmp VALUES(@column)
end
FETCH NEXT FROM ColumnCursor INTO @column
end
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;
有没有更简单的方法来实现这一点?