hash a SQL row?

I had to develop a solution to compare table structures and run a procedure to import the difference between the tables.

I used below code to select the data

--> table structures

create table #table1 (
campo varchar(10)
,campo1 varchar(10)
)

create table #table2 (
campo varchar(10)
,campo1 varchar(10)
)

--> Insert values

insert into #table1 values ('bruno',1)
insert into #table1 values ('bruno',2)
insert into #table2 values ('bruno',1)
insert into #table2 values ('bruna',2)

--> Create a hash column to compare

select *,HASHBYTES('SHA1', (select z.* FOR XML RAW)) as hash
    into #compare1
 from #table1 z 

select *,HASHBYTES('SHA1', (select k.* FOR XML RAW)) as hash
    into #compare2
 from #table2 k 

--> check the lines that has any difference

select * from  #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null )

Maybe this is useful for someone needing the same thing Find code explaned above here


There are CHECKSUM(*), BINARY_CHECKSUM(*) and CHECKSUM_AGG. They do CRC32 like checkum, but for detecting changes to a row it should be more than enough (you are talking about 1 in 4 billion chances for a false negative collision).

Doing a cryptographic hash using HASHBYTES requires you to construct an expression representing the 'row'.


If you have SQL Server 2008 or newer you could use:

SELECT HASHBYTES('SHA1', (SELECT TOP 1 * FROM dbo.Table FOR XML RAW))

or

SELECT  
    HASHBYTES('SHA1',(
        SELECT  * 
        FROM    dbo.myTable as  tableToHash 
        where   tableToHash.myUniqueKey=myTable.myUniqueKey 
        FOR XML RAW
    ))                                              as  rowSHA1
from    dbo.myTable;