SqlServer checksum in C #

I am using the chechsum function in sql server 2008 R2 and I would like to get the same int values ​​in a C # application. Is there an equivalent method in C # that returns values ​​like sql checksum function? Thanx

+7
c # sql-server checksum
source share
4 answers

CHECKSUM docs do not disclose how it computes the hash. If you want to use a hash that you can use in T-SQL and C #, select the algorithms supported in HashBytes

+1
source share

The SQL Server forum on this page says:

The built-in CHECKUM function in SQL Server is based on 4-bit left-handed xor operations. See this post for more information.

I managed to port BINARY_CHECKSUM to C # and it seems to work ... I will look at a simple CHECKSUM later ...

 private int SQLBinaryChecksum(string text) { long sum = 0; byte overflow; for (int i = 0; i < text.Length; i++) { sum = (long)((16 * sum) ^ Convert.ToUInt32(text[i])); overflow = (byte)(sum / 4294967296); sum = sum - overflow * 4294967296; sum = sum ^ overflow; } if (sum > 2147483647) sum = sum - 4294967296; else if (sum >= 32768 && sum <= 65535) sum = sum - 65536; else if (sum >= 128 && sum <= 255) sum = sum - 256; return (int)sum; } 
+9
source share

T-SQL documentation does not indicate which algorithm checksum() is used outside of this:

CHECKSUM calculates a hash value called a checksum from its argument list. The hash value is intended for use in the construction of hash indexes. If the arguments for CHECKSUM are columns and the index is built on the calculated value of CHECKSUM, the result is a hash index. This can be used to search for equality across columns.

It is not possible to compute an MD5 hash because its return value (computed hash) is a 32-bit integer; the MD5 hash is 128 bits long.

+2
source share

If you need to do a checksum in 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 check:

 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.

0
source share

All Articles