当inserint值为varbinary时重复出现问题

MoS*_*She 4 sql duplicates varbinary sql-server-2008

我们面临一个非常奇怪的问题.

当表列如下时,我们的mssql 2008 R2 db中有一个表:

  1. userId - int
  2. userName - varbinary(256)
  3. userType - int

和userName列是唯一的

我们再次对表格执行以下查询:

insert into table_name (userId, userName, userType) values ( 1 ,  0x5942C803664B00, 0)
Run Code Online (Sandbox Code Playgroud)

在该查询之后,我们执行以下查询:

insert into table_name (userId, userName, userType) values ( 2 ,  0x5942C803664B, 0)
Run Code Online (Sandbox Code Playgroud)

我们得到以下错误:

无法在对象'table_name'中插入具有唯一索引'table_name _userName_u'的重复键行.

虽然0x5942C803664B和0x5942C803664B00是不同的值?

任何的想法 ?

Ric*_*iwi 6

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
Run Code Online (Sandbox Code Playgroud)

为了比较的目的,最后一个字节(8位为0)被认为是无关紧要的.这就是你得到的原因

select CASE WHEN 'abc ' = 'abc' then 'SAME' else 'DIFFERENT' end
-- select case when 0x5942C803664B = 0x5942C803664B00 then 'same' else 'different' end

result
======
SAME
Run Code Online (Sandbox Code Playgroud)

要使尾随的零字节显着,您可以欺骗并向两个部分添加相同的内容.

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
Run Code Online (Sandbox Code Playgroud)