2014-01-16 62 views
8

這可能是一個愚蠢的問題,但任何人都可以解釋爲什麼SQL返回'False'用於SQL字符串對比IF

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

但返回'True'

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

編輯:

我m使用SQL Server 2008 R2

+1

是你使用MySQL或其他數據庫? – Melon

+0

+1不傻,實際上有趣:) – everton

+0

我會認爲這是一個BUG :) –

回答

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. 
+0

我很確定這是用'SET ANSI_PADDING'控制的。 –

+0

有點難以放入這個評論框,但是:SET ANSI_PADDING ON; IF 'TEST'= '測試' \t SELECT '真' ELSE \t SELECT '假' ENDIF SET ANSI_PADDING OFF; IF「TEST」 =「TEST」 \t選擇「真」 ELSE \t選擇「假」 ENDIF仍然得到真真 – Snake

2

我想這是因爲數據庫會截斷尾隨空格,但不會引導空格。

一些documentation支持這種猜測。

的SQL Server遵循ANSI/ISO SQL-92規範對如何比較字符串 與空間(第8.2節 ,一般3#規則)。 ANSI標準要求填充字符 用於比較的字符串,以便它們的長度在比較之前匹配 。填充直接影響WHERE 和HAVING子句謂詞以及其他Transact-SQL字符串 比較的語義。例如,對於大多數比較操作,Transact-SQL將字符串'abc'和 'abc'視爲等效。

+0

我正在等待OP的數據庫平臺的答案來支持。 –

+0

引用的文檔與您的猜測相矛盾,但仍然是一個有用的答案。 –