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
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
6条答案
按热度按时间6fe3ivhb1#
On SQL Server Forum, at this page , it's stated:
The built-in CHECKUM function in SQL Server is built on a series of 4 bit left rotational xor operations. See this post for more explanation.
I was able to port the BINARY_CHECKSUM to c# and it seems to be working... I'll be looking at the plain CHECKSUM later...
4bbkushb2#
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 HashBytespx9o7tmv3#
The T-SQL documentation does not specify what algorithm is used by
checksum()
outside of this:CHECKSUM computes a hash value, called the checksum, over its list of arguments. The hash value is intended for use in building hash indexes. If the arguments to CHECKSUM are columns, and an index is built over the computed CHECKSUM value, the result is a hash index. This can be used for equality searches over the columns.
It's unlikely to compute an MD5 hash, since its return value (the computed hash) is a 32-bit integer; an MD5 hash is 128 bits in length.
368yc8dk4#
In case you need to do a checksum on a GUID, change dna2's answer to this:
With a byte array, the value from SQL will match the value from C#. To test:
vs SQL:
both answers will be -1897092103.
z9gpfhce5#
@Dan's implementation of BinaryChecksum can be greatly simplified down in c# down to
This also makes it clearer what the algorithm is doing. For each character, a 4 bit circular shift then an xor with character's byte
bq8i3lrv6#
Based on other answers and comments, I made a version with some fixes for:
C# >= 11 (note the Unsigned right-shift operator >>>)
C# < 11