TSQL HASHBYTES 用法

来源:互联网 发布:访客网络有必要开吗 编辑:程序博客网 时间:2024/05/21 09:25

HashBytes 使用Hash 算法,能够产生高质量的Hash值,大幅度提高识别数据相异的准确性,但是HashBytes函数无法提供100%的准确度,如果业务逻辑要求不允许有误差,那么不要使用任何Hash 函数,只要是Hash函数,就会存在冲突。HashBytes 函数对于相同的文本,有时会产生不同的hash value。

When an MD5 hash algorithm is specified, the probability of HashBytes returning the same result for two different inputs is much lower than that of CHECKSUM.

HashBytes 只能有一个输入参数,参数的数据类型是varchar、nvarchar 或 varbinary,并且输入字符的最大字节数量是8000Bytes。Hash value的计算跟Data type相关:varchar 和nvarchar的hashbytes是不同的。

一,算法

使用 HashBytes需要指定算法,MS内置7种计算HashValue的算法,推荐使用MD5来计算数据的差异。

  HASHBYTES ( '<algorithm>', { @input | 'input' } )   <algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

输入参数的数据类型为 varchar、nvarchar 或 varbinary,输入参数的字节数量不能超过8000bytes.

HashBytes函数的返回值的数据类型是 varbinary ,不同的算法返回的字节长度是不同的

The output conforms to the algorithm standard: 128 bits (16 bytes) for MD2, MD4, and MD5; 160 bits (20 bytes) for SHA and SHA1; 256 bits (32 bytes) for SHA2_256, and 512 bits (64 bytes) for SHA2_512.

二,影响HashBytes函数的因素

1,HashBytes函数受Data Type 的影响

select HASHBYTES('SHA1',N'123abc') as HashNChar, HASHBYTES('SHA1','123abc') as HashChar;

2,HashBytes函数受字符大小写的影响

select hashbytes('SHA1','eric') as UpperCase,hashbytes('SHA1','Eric') as LowerCase

3,输入字符串的大小不能超过8000Bytes,如果输入字符串的字节数量大于8000Bytes,那么HashBytes 会将超过8000Bytes的字符舍弃,只对前8000Bytes进行Hash计算。SQL Server 不会提供任何提示或warning,在使用时,必须保证,输入字符串的字节数量不能超过8000。

如果是Unicode字符,那么输入字符串字符数量不能超过4000个;如果是varchar字符,那么输入字符串的数量不能超过8000个。

select hashbytes('SHA1',replicate('eric',2000)) ,hashbytes('SHA1',replicate('eric',4000))

0 0
原创粉丝点击