c# - SQL WHERE 子句匹配带有尾随空格的值

标签 c# sql sql-server database sql-server-2008

在 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.

Source

关于c# - SQL WHERE 子句匹配带有尾随空格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166159/

相关文章:

php - 当我已经计算了总行数时,如何计算 mysql 中分组的行数

mysql - 哪个 MYSQL Join 包含不存在的记录

sql - SSIS - 获取行的最新记录

sql-server - 获取 proc 选择输出的模式

c# - 如何拦截内置 Office 功能区控件的单击

c# - msi 安装程序出现错误 2908

具有 Postgres 数据库和适当大小写的 C# POCO 类(不使用 Entity Framework )

c# - iTextSharp : C# image to PDF - Spread big asp chart on more than one page

sql - 如何获取sql server中两个日期之间的开始日期和结束日期

java - 无法使用 Schemacrawler 连接到 MSSQL