查询后,SQL Server会自动修剪nvarchar字段吗? [英] Does SQL Server automatically trim nvarchar fields upon query?

查看:135
本文介绍了查询后,SQL Server会自动修剪nvarchar字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询:

select '[' + p.Firstname + ']' from Person p
where p.Firstname = 'Johanne'

在表中,我有多个人有这个名字,并且有些在值上有一个尾随空格(错误插入的值,它将被更正)。

In the table, I have multiple personne who have this firstname, and some have a trailing space on the value (bad insertion of the values, it will be corrected).

为什么这个查询给我这个结果(我插入括号可视化空格):

Why then does this query bring me this result (I inserted the brackets to visualize the spaces) :

[Johanne]
[Johanne ]
[Johanne ]
[Johanne]

这是一个配置吗?真正的查询来自实体框架6,但是这个例子也是这样。如何防止它?

Is this a configuration thing ? The real query comes from entity framework 6, but this example does it also. How can I prevent it ?

谢谢!

编辑:我可以使用EF6和 System.Data.Entity.SqlServer.SqlFunctions.DataLength 这样的方法:

I could make it work using EF6 and the System.Data.Entity.SqlServer.SqlFunctions.DataLength method like this:

ctx.Person.FirstOrDefault(p => p.FirstName == "Johanne" && SqlFunctions.DataLength(p.FirstName) == "Johanne".Length);


推荐答案

SQL Server遵循ANSI / ISO SQL-92规范(第8.2节,通则3)关于如何比较字符串与空格。 ANSI标准要求用于比较中使用的字符串的填充,以便在比较它们之前匹配它们的长度。填充直接影响WHERE和HAVING子句谓词以及其他Transact-SQL字符串比较的语义。例如,Transact-SQL将字符串'abc'和'abc'视为大多数比较操作的等效项。

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.

此规则的唯一例外是LIKE谓词。当LIKE谓词表达式的右侧具有带有尾部空格的值时,SQL Server不会在比较发生之前将两个值填充到相同的长度。因为根据定义,LIKE谓词的目的是为了便于模式搜索而不是简单的字符串相等性测试,这并不违反前面提到的ANSI SQL-92规范的部分。

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.

请参阅: http:// support2.microsoft.com/kb/316626/en-us

这篇关于查询后,SQL Server会自动修剪nvarchar字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆