I ran into something a little odd this morning and thought I'd submit it for commentary.
Can someone explain why the following SQL query prints 'equal' when run against SQL 2008. The db compatibility level is set to 100.
if '' = ' '
print 'equal'
else
print 'not equal'
And this returns 0:
select (LEN(' '))
It appears to be auto trimming the space. I have no idea if this was the case in previous versions of SQL Server, and I no longer have any around to even test it.
I ran into this because a production query was returning incorrect results. I cannot find this behavior documented anywhere.
Does anyone have any information on this?
There was a similar question a while ago where I looked into a similar problem here
Instead of LEN(' '), use DATALENGTH(' ') - that gives you the correct value.
The solutions were to use a LIKE clause as explained in my answer in there, and/or include a 2nd condition in the WHERE clause to check DATALENGTH too.
Have a read of that question and links in there.
I found this blog article which describes the behavior and explains why.
More information also available in MSKB316626
How to distinct records on select with fields char/varchar on sql server: example:
expected
mykey (int) | myfield (varchar10)
1 | 'data '
obtained
mykey | myfield
1 | 'data' 2 | 'data '
even if I write
select mykey, myfield from mytable where myfield = 'data'
(without final blank) I get the same results.how I solved? In this mode:
and if there is an index on myfield, it'll be used in each case.
I hope it will be helpful.
To compare a value to a literal space, you may also use this technique as an alternative to the LIKE statement:
Sometimes one has to deal with spaces in data, with or without any other characters, even though the idea of using Null is better - but not always usable. I did run into the described situation and solved it this way:
... where ('>' + @space + '<') <> ('>' + @space2 + '<')
Of course you wouldn't do that fpr large amount of data but it works quick and easy for some hundred lines ...
Herbert
varchar
s and equality are thorny in TSQL. TheLEN
function says:You need to use
DATALENGTH
to get a truebyte
count of the data in question. If you have unicode data, note that the value you get in this situation will not be the same as the length of the text.When it comes to equality of expressions, the two strings are compared for equality like this:
It's the middle step that is causing unexpected results - after that step, you are effectively comparing whitespace against whitespace - hence they are seen to be equal.
LIKE
behaves better than=
in the "blanks" situation because it doesn't perform blank-padding on the pattern you were trying to match:Will give
eq
while:Will give
ne
Careful with
LIKE
though: it is not symmetrical: it treats trailing whitespace as significant in the pattern (RHS) but not the match expression (LHS). The following is taken from here: