In SQL Server 2008 I have a table called Zone
with a column ZoneReference varchar(50) not null
as the primary key.
If I run the following query:
select '"' + ZoneReference + '"' as QuotedZoneReference from Zone where ZoneReference = 'WF11XU'
I get the following result:
"WF11XU "
Note the trailing space.
How is this possible? If the trailing space really is there on that row, then I’d expect to return zero results, so I’m assuming it’s something else that SQL Server Management Studio is displaying weirdly.
In C# code calling zoneReference.Trim()
removes it, suggesting it is some sort of whitespace character.
Can anyone help?
Advertisement
Answer
That’s the expected result: in SQL Server the =
operator ignores trailing spaces when making the comparison.
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.