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?
varchars and equality are thorny in TSQL. TheLENfunction says:You need to use
DATALENGTHto get a truebytecount 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.
LIKEbehaves better than=in the “blanks” situation because it doesn’t perform blank-padding on the pattern you were trying to match:Will give
eqwhile:Will give
neCareful with
LIKEthough: 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: