使用IF进行SQL字符串比较

时间:2014-01-16 14:31:01

标签: sql sql-server string if-statement

这可能是一个愚蠢的问题,但任何人都可以解释为什么SQL为

返回'False'
IF 'test' = ' test' -- notice leading space
 SELECT 'True'
ELSE
 SELECT 'False'

但是

返回'True'
IF 'test' = 'test ' -- notice trailing space
 SELECT 'True'
ELSE
 SELECT 'False'

编辑:

我正在使用SQL Server 2008 R2

2 个答案:

答案 0 :(得分:7)

忽略尾随空格。

如果你想真正测试它们是否相同,那么就像这样:

DECLARE @foo nvarchar(50) = 'foo'
DECLARE @foo2 nvarchar(50) = 'foo ' -- trailing space

IF @foo = @foo2 AND DATALENGTH(@foo) = DATALENGTH(@foo2) --LEN ignores trailing spaces
    SELECT 'true'
ELSE
    SELECT 'false'

为什么你的例子是真的:

http://www.timvw.be/2013/04/27/the-curious-case-of-trailing-spaces-in-sql/

根据http://www.andrew.cmu.edu/user/shadow/sql/sql1992.txt

 3) The comparison of two character strings is determined as fol-
        lows:

        a) If the length in characters of X is not equal to the length
          in characters of Y, then the shorter string is effectively
          replaced, for the purposes of comparison, with a copy of
          itself that has been extended to the length of the longer
          string by concatenation on the right of one or more pad char-
          acters, where the pad character is chosen based on CS. If
          CS has the NO PAD attribute, then the pad character is an
          implementation-dependent character different from any char-
          acter in the character set of X and Y that collates less
          than any string under CS. Otherwise, the pad character is a
          .

        b) The result of the comparison of X and Y is given by the col-
          lating sequence CS.

        c) Depending on the collating sequence, two strings may com-
          pare as equal even if they are of different lengths or con-
          tain different sequences of characters. When the operations
          MAX, MIN, DISTINCT, references to a grouping column, and the
          UNION, EXCEPT, and INTERSECT operators refer to character
          strings, the specific value selected by these operations from
          a set of such equal values is implementation-dependent.

答案 1 :(得分:2)

我想这是因为数据库会截断尾随空格,而不是前导空格。

有些documentation支持猜测。

  

SQL Server遵循ANSI / ISO SQL-92规范(第8.2节,   ,关于如何比较字符串的一般规则#3)   有空格。 ANSI标准要求填充字符   比较中使用的字符串,以便它们的长度匹配   比较它们。填充直接影响WHERE的语义   和HAVING子句谓词和其他Transact-SQL字符串   比较。例如,Transact-SQL认为字符串'abc'和   'abc'与大多数比较操作相同。