views:

41

answers:

3
+5  Q: 

len of varbinary

hello,

would someone please explain why select len(0x0a000b) returns 3? does len count bytes? and why select left(0x0a000b, 1) returns nothing? i expected 0x0a (if len counts bytes)...

i am using mssql 2005

thanks konstantin

+2  A: 

left is the string operator and so it doesn't work on binary data in the way you expect it to work, use substring(@v, 1, 1) instead

len, on the other hand, returns the length of binary data (apart of other data types); although, there's a very interesting exception to strings, when we measure the length of a string using this command it first performs rtrim on it; so len('a ') would return 1

Denis Valeev
not true...select left(0x45000b, 1)
SQLMenace
Absolutely! Not the way you'd expect it to work.
Denis Valeev
@SQLMenace Try `select substring(0x45000b, 1, 1)` which returns 0x45 but your select returns 'E'
Emtucifor
@Emtucifor This is correct, because E = 0x45 = 69d = 105o
Denis Valeev
@Denis- Yes I know it's correct, I was just confused why SQLMenace said "not true." If you hadn't mentioned using substring instead of left, I would have.
Emtucifor
@Emtucifor Well, SQLMenace was referring to the fact that `left` operator was actually accepting varbinary as its input but my answer made a reader think that it wouldn't. Or something to that effect. Doesn't really matter. :)
Denis Valeev
@Denis Oh... yes it works, it just converts to varchar which could be unexpected. Exactly as you said. People should read whole sentences before reacting to parts of them. :)
Emtucifor
+2  A: 

select len(0x0a000b) is returning the length of a string represented by the three bytes 0x0a, 0x00, and 0x0b.

select left(0x0a000b, 1) returns the left-most character of the string, which is a newline character.

Note that select case when left(0x0a000b, 1) = 0x0a then 1 else 0 end returns 1, which indicates you are, indeed, getting the newline character.

Edit: Please see the comments below for additional details.

kbrimington
Please update to mention that left will return varchar instead of binary, and to use substring instead.
Emtucifor
+1  A: 

would someone please explain why select len(0x0a000b) returns 3

it is 3 characters
0x means it is binary

0a character 1
00 character 2
0b character 3

you have a non printable character, I believe 0a is a carriage return, run this

select left(0x45000b, 1)
SQLMenace