在 SQL Server 2008 中,我有一个名为 Zone
的表,其中有一列 ZoneReference varchar(50) not null
作为主键。
如果我运行以下查询:
select '"' + ZoneReference + '"' as QuotedZoneReference
from Zone
where ZoneReference = 'WF11XU'
我得到以下结果:
"WF11XU "
注意尾随空格。
这怎么可能?如果该行上确实存在尾随空格,那么我希望返回零 结果,因此我假设这是 SQL Server Management Studio 奇怪地显示的其他内容。
在 C# 代码中调用 zoneReference.Trim()
将其删除,表明它是某种空白字符。
有人能帮忙吗?
最佳答案
这是预期的结果:在 SQL Server 中,=
运算符在进行比较时会忽略尾随空格。
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.
关于c# - SQL WHERE 子句匹配带有尾随空格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166159/