4

例如,如果我有这些数据:

CREATE TABLE FooBar ( Name varchar(16) )

INSERT FooBar SELECT 'test@test.com'

以下查询不会返回我期望的结果:

SELECT * FROM FooBar WHERE Name = 'test@test.com       '  -- Returns the row

SELECT * FROM FooBar WHERE Name LIKE 'test@test.com '  -- Nothing Returned

SELECT * FROM FooBar WHERE Name = ' test@test.com' -- Nothing Returned

为什么=(我假设这意味着完全等于)最后有额外的空间返回数据,而 aLIKE没有?

4

1 回答 1

5

Seing the standard it depends on padding (The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them)

SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.

The only exception to this rule is the LIKE predicate. When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs. Because the purpose of the LIKE predicate, by definition, is to facilitate pattern searches rather than simple string equality tests, this does not violate the section of the ANSI SQL-92 specification mentioned earlier.

See also how SQL Server compares strings with trailing spaces

于 2012-09-04T19:18:08.863 回答