我们面临一个非常奇怪的问题。
当表列如下时,我们的 mssql 2008 R2 数据库中有一张表:
并且 userName 列是唯一的
我们再次对表执行以下查询:
insert into table_name (userId, userName, userType) values ( 1 , 0x5942C803664B00, 0)
在该查询之后,我们执行以下查询:
insert into table_name (userId, userName, userType) values ( 2 , 0x5942C803664B, 0)
我们得到以下错误:
Cannot insert duplicate key row in object 'table_name ' with unique index 'table_name _userName_u'.
虽然 0x5942C803664B 和 0x5942C803664B00 是不同的值??
任何的想法 ?
最佳答案
varbinary 列中的尾随“零字节” 0x00 与 varchar 列中的尾随空格“”一样无关紧要。因此,您的值实际上是重复的。
换句话说,您的两个值是(按字节顺序)
1 2 3 4 5 6 7 --- bytes in the binary value
59 42 C8 03 66 4B
59 42 C8 03 66 4B 00
出于比较的目的,最后一个字节(8 位 0)被认为是无关紧要的。这和你得到的原因是一样的
select CASE WHEN 'abc ' = 'abc' then 'SAME' else 'DIFFERENT' end
-- select case when 0x5942C803664B = 0x5942C803664B00 then 'same' else 'different' end
result
======
SAME
要使尾随的零字节有意义,您可以作弊并在两个部分中添加相同的内容。
select case when 0x5942C803664B + 0xff = 0x5942C803664B00 + 0xff
then 'same'
else 'different' end -- different
select case when 0x5942C80366AA + 0xff = 0x5942C80366AA + 0xff
then 'same'
else 'different' end -- same
关于sql - 将值插入到 varbinary 时出现重复问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16210694/