Here's a script I just whipped up that will create a function that you can call from inside your trigger to get a compare query. You can then run that query and insert the results into a temp table and you do whatever you need to do based on whether the row changed or not.
create function GetChangedRowsQuery(
@TableName varchar(50),
@PrimaryKeyColumnName varchar(50),
@RowVersionColumnName varchar(50) = ''
)
returns varchar(max)
as
begin
declare
@ColumnName varchar(50),
@GetChangedRowsQuery varchar(max)
select @GetChangedRowsQuery =
'select isnull(a.' + @PrimaryKeyColumnName + ', b.' + + @PrimaryKeyColumnName + ')
from #inserted a
full join #deleted b on a.' + @PrimaryKeyColumnName + ' = b.' + @PrimaryKeyColumnName + '
where '
declare ColumnCursor cursor Read_Only
for select Name
from Sys.columns
where object_id = Object_Id('Member')
open ColumnCursor
fetch next from ColumnCursor into @ColumnName
while @@FETCH_STATUS = 0
begin
if (@ColumnName != @PrimaryKeyColumnName and @ColumnName != @RowVersionColumnName)
begin
select @GetChangedRowsQuery = @GetChangedRowsQuery + '((a.' + @ColumnName + ' != b.' + @ColumnName + ' or a.' + @ColumnName + ' is null or b.' + @ColumnName + ' is null) and (a.' + @ColumnName + ' is not null or b.' + @ColumnName + ' is not null))' + char(13) + ' or '
end
fetch next from ColumnCursor into @ColumnName
end
close ColumnCursor
deallocate ColumnCursor
select @GetChangedRowsQuery = substring(@GetChangedRowsQuery, 0, len(@GetChangedRowsQuery) -7)
return @GetChangedRowsQuery
end
Then you can create your trigger to look like this
create trigger TestTrigger on Member for Insert, Update, Delete
as
begin
//We can't access the inserted or deleted tables from inside the exec statement
//Dump that data into temp tables so you we can
select *
into #Inserted
from Inserted
select *
into #Deleted
from Deleted
declare @GetChangedRowsQuery varchar(max)
select @GetChangedRowsQuery = dbo.GetChangedRowsQuery('Member', 'MemberId', '')
select @GetChangedRowsQuery
create table #Temp (PrimaryKey int)
insert into #Temp (PrimaryKey)
exec (@GetChangedRowsQuery)
//Do what you need to do with the rows that have or haven't been updated
drop table #Temp
end
go
I've updated this answer about a dozen times now, and I think I've worked the bugs out, but I make no guarantees.
A query like this could be crushing to performance, and I'm not sure I'd actually recommend implementing it, but it was fun to create.
group by
fields and usecount
; adding thehaving
clause set tocount(unique_field) >=2
will show you duplicates. Though, table schema matters as you won't be able to take the same query and use it on a different table. What you're asking for is aSELECT ALL EXCEPT <fieldset> FROM ...
syntax, which I've been asking for ISO-SQL to adopt for many years.