hash a SQL row?

后端 未结 4 575
情歌与酒
情歌与酒 2020-12-29 23:32

Is there a way to md5sum a row in a SQL table to check whether any column has been modified?

I would like to check whether any particular column has been changed ver

相关标签:
4条回答
  • 2020-12-29 23:36

    Get all row, do the md5 of each column and compare it with the md5 of the correspondent column in the previous data.

    0 讨论(0)
  • 2020-12-29 23:59

    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;
    
    0 讨论(0)
  • 2020-12-30 00:01

    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'.

    0 讨论(0)
  • 2020-12-30 00:02

    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

    0 讨论(0)
提交回复
热议问题