gpt4 book ai didi

SQL Server WHERE 条件不考虑空格

转载 作者:行者123 更新时间:2023-12-05 01:13:04 25 4
gpt4 key购买 nike

我的名字和姓氏后面有空格。我有两个 SQL 查询——第一个查询返回结果,即使我搜索时没有空格。 (第一个查询返回不需要的结果)。

  1. 此行为在所有版本的 SQL Server 中都一致吗?
  2. 这是已知行为吗? SQL Server 2008 R2msdn 中是否有记录?

代码

DECLARE @NameTable TABLE (first_name varchar(40),last_name varchar(40))
INSERT INTO @NameTable VALUES ('STEVEN ','STANLEY ');


--QUERY 1
SELECT first_name AS [FirstName], last_name AS [LastName]
FROM @NameTable A
WHERE (first_name = 'STEVEN')
AND (last_name = 'STANLEY')


--QUERY 2
SELECT first_name AS [FirstName], last_name AS [LastName]
FROM @NameTable A
WHERE (( ISNULL(first_name,'')+' ' +ISNULL(last_name,'') ) = 'STEVEN STANLEY')

--QUERY 3 (With LTRIM and RTRIM)
SELECT first_name AS [FirstName], last_name AS [LastName]
FROM @NameTable A
WHERE (( ISNULL(LTRIM(RTRIM(first_name)),'')+' ' +ISNULL(LTRIM(RTRIM(last_name)),'') ) = 'STEVEN STANLEY')

引用:

  1. DataLength
  2. In SQL Server 2005, what is the difference between len() and datalength()?

最佳答案

引用http://support.microsoft.com/kb/316626

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.

如果你想避免这种情况,你可以添加一个附加条件,如下所示

引用:DataLength

SELECT first_name AS [FirstName], last_name AS [LastName],first_name+last_name,LEN(first_name+last_name)
FROM @NameTable A
WHERE (first_name = 'STEVEN') and DATALENGTH(first_name)=DATALENGTH(RTRIM(first_name))
AND (last_name = 'STANLEY') and DATALENGTH(last_name)=DATALENGTH(RTRIM(last_name))

关于SQL Server WHERE 条件不考虑空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com