Generate a hash for a set of rows in sql server

前端 未结 4 691
春和景丽
春和景丽 2021-01-17 12:24

Is there any way in SQL Server 2012 to generate a hash of a set of rows and columns?

I want to generate a hash, store it on the parent record. The when an update co

相关标签:
4条回答
  • 2021-01-17 12:45

    Another approach:

    -- compute a single hash value for all rows of a table
    begin
    
        set nocount on;
    
        -- init hash variable
        declare @tblhash varchar(40);
        set @tblhash = 'start';
    
        -- compute a single hash value
        select @tblhash = sys.fn_varbintohexsubstring(0, hashbytes('sha1',(convert(varbinary(max),@tblhash+
        (select sys.fn_varbintohexsubstring(0,hashbytes('sha1',(convert(varbinary(max),
        -- replace 'select *' if you want only specific columns to be included in the hash calculation
        -- [target table] is the name of the table to calc the hash from
        -- [row_id] is the primary key column within the target table
        -- modify those in the next lines to suit your needs:
        (select * from [target_table] obj2 where obj2.[row_id]=obj1.[row_id] for xml raw)
        ))),1,0))
        ))),1,0)
        from [target_table] obj1;
    
        set nocount off;
    
        -- return result
        select @tblhash as hashvalue;
    
    end;
    
    0 讨论(0)
  • 2021-01-17 12:46

    For single row hashes:

    select HASHBYTES('md5', Name + Description + AnotherColumn)
    FROM MyChildTable WHERE ParentId = 2
    

    for table checksum:

    select sum(checksum(Name + Description + AnotherColumn)*1.0)
    FROM MyChildTable WHERE ParentId = 2
    
    0 讨论(0)
  • 2021-01-17 12:47

    You can use the CHECKSUM_AGG aggregate. it is made for that purpose.

    0 讨论(0)
  • 2021-01-17 12:53
    select HashBytes('md5',convert(varbinary(max),(SELECT * FROM MyChildTable WHERE ParentId = 2 FOR XML AUTO)))
    

    but HashBytes is limited to 8000 bytes only... you can make a function to get de Md5 for every 8000 bytes....

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