tags:

views:

129

answers:

2

I have a table (t) with a column (c) defined as varchar 20, containing the values 'a', 'b' and 'c'

If I execute the following sql, a value is returned:

select * from table where c = 'a    '

Why?

I assume it's casting/trimming the parameter in some way, but why?

How would I really search for 'a '

+1  A: 

To compare it to a varchar column, your string literal must also be a varchar type. Varchar does trim extra ending white space. It varies, hence VARchar. The plain the char type does not trim the whitespace, and will actually append extra spaces on the end of a literal if need be. You can check for this (and fix your search with the LEN() function:

 declare @a varchar(20) = 'a     '
 select * from t where c = @a and len(@a) = Len(c)
Joel Coehoorn
I found that using len didn't solve this - if I did:declare @a varchar(20)set @a = 'a 'select len(c), len(@a), * from t where c = @a and len(c) = len(@a)it returned a row, and the len values were both 4If I used datalength however, it didn't succeed.Thanks for the pointer.
hitch
+1  A: 

Trailing space is specified to be handled in a special way in the ANSI SQL Standard:

http://support.microsoft.com/default.aspx/kb/316626

http://support.microsoft.com/kb/154886/EN-US/

This behavior is effectively the same for both char and varchar.

Cade Roux