sql - duplicate issue when inserint value to varbinary -


we face weird issue.

we have 1 table in our mssql 2008 r2 db when table column follow:

  1. userid - int
  2. username - varbinary(256)
  3. usertype - int

and username column unique

we preform following query again table:

insert table_name (userid, username, usertype) values ( 1 ,  0x5942c803664b00, 0) 

and after query following query :

insert table_name (userid, username, usertype) values ( 2 ,  0x5942c803664b, 0) 

and following error:

cannot insert duplicate key row in object 'table_name ' unique index 'table_name _username_u'.

although 0x5942c803664b , 0x5942c803664b00 different values??

any idea ?

the trailing "zero-bytes" 0x00 in varbinary column insignificant trailing spaces " " in varchar column. therefore, values duplicates.

in other words, 2 values (in byte order)

1  2  3  4  5  6  7  --- bytes in binary value 59 42 c8 03 66 4b 59 42 c8 03 66 4b 00 

the last byte (8 bits of 0) considered insignificant purposes of comparison. same reason why get

select case when 'abc ' = 'abc' 'same' else 'different' end -- select case when 0x5942c803664b = 0x5942c803664b00 'same' else 'different' end  result ====== same 

to make trailing zero-bytes significant, can cheat , add equally both parts.

select case when 0x5942c803664b + 0xff = 0x5942c803664b00 + 0xff             'same'             else 'different' end   -- different  select case when 0x5942c80366aa + 0xff = 0x5942c80366aa + 0xff             'same'             else 'different' end   -- same 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -