我有一个简单的问题:
print HASHBYTES('SHA1', 'az09123')
告诉我:
0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3enter
我把它放在名为OwnerEn
的navchar字段中然后我试试这个:
SELECT * FROM AspNetUsers WHERE OwnerEn = HASHBYTES('SHA1', 'az09123');
没有结果,它是空的
但这给了我结果:
SELECT * FROM AspNetUsers WHERE OwnerEn = '0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3';
第一个sql语句有什么问题?
答案 0 :(得分:1)
正如Oscar在评论中提到的那样,您看不到任何结果,因为nvarchar
值0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3
与二进制值0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3
不同。
理想情况下,您可以将哈希值存储在适当的binary
或varbinary
数据类型列中,但如果您无法在数据库中更改哈希值,则需要convert
nvarchar
值为binary
或varbinary
(反之亦然),以便实际比较这两个值:
请注意1
末尾的convert
,以指定您希望在开头添加0x
nvarchar
至varbinary
:
convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1)
varbinary
至nvarchar
:
convert(nvarchar(100),hashbytes('SHA1', 'az09123'),1)
以下脚本对此进行了演示:
select hashbytes('SHA1', 'az09123') as BinaryHash
,convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1) as NvarcharHash
,case when hashbytes('SHA1', 'az09123') = '0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3'
then 'Match'
else 'No Match'
end as UnconvertedMatchTest
,case when hashbytes('SHA1', 'az09123') = convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1)
then 'Match'
else 'No Match'
end as ConvertedMatchTest
输出:
+--------------------------------------------+--------------------------------------------+----------------------+--------------------+
| BinaryHash | NvarcharHash | UnconvertedMatchTest | ConvertedMatchTest |
+--------------------------------------------+--------------------------------------------+----------------------+--------------------+
| 0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3 | 0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3 | No Match | Match |
+--------------------------------------------+--------------------------------------------+----------------------+--------------------+
答案 1 :(得分:0)