Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlServer Checksum in C#

I'm using the chechsum function in sql server 2008 R2 and I would like to get the same int values in a C# app. Is there any equivalent method in c# that returns the values like the sql checksum function? Thanx

like image 914
Andres Avatar asked Sep 18 '13 16:09

Andres


2 Answers

CHECKSUM docs don't disclose how it computes the hash. If you want a hash you can use in T-SQL and C#, pick from the algorithms supported in HashBytes

like image 58
Matt Stephenson Avatar answered Oct 11 '22 05:10

Matt Stephenson


In case you need to do a checksum on a GUID, change dna2's answer to this:

private int SQLBinaryChecksum(byte[] text)

With a byte array, the value from SQL will match the value from C#. To test:

var a = Guid.Parse("DEAA5789-6B51-4EED-B370-36F347A0E8E4").ToByteArray();
Console.WriteLine(SQLBinaryChecksum(a));

vs SQL:

select BINARY_CHECKSUM(CONVERT(uniqueidentifier,'DEAA5789-6B51-4EED-B370-36F347A0E8E4'))

both answers will be -1897092103.

like image 21
mikewishart Avatar answered Oct 11 '22 05:10

mikewishart