3

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 '

4

3 回答 3

1

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)
于 2009-09-04T03:36:15.110 回答
1

在 ANSI SQL 标准中指定以特殊方式处理尾随空格:

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

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

对于 char 和 varchar,这种行为实际上是相同的。

于 2009-09-04T03:37:52.300 回答
0

我使用了简单的解决方案:

declare @a varchar(20) = 'a     '
select * from t where c + '$' = @a  + '$'
于 2011-12-21T16:18:07.583 回答