加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server-2008 – 空字符串:为什么或何时“等于”?

发布时间:2020-12-12 06:20:08 所属栏目:MsSql教程 来源:网络整理
导读:谁能解释原因 select case when '' = ' ' then 1 else 0 end,LEN(''),LEN(' '),DATALENGTH(''),DATALENGTH(' '); 产量 ----------- ----------- ----------- ----------- -----------1 0 0 0 1 这有趣的结果是在 create table test ( val varchar(10) );inser
谁能解释原因
select case when '' = ' ' then 1 else 0 end,LEN(''),LEN(' '),DATALENGTH(''),DATALENGTH(' ');

产量

----------- ----------- ----------- ----------- -----------
1           0           0           0           1

这有趣的结果是在

create table test ( val varchar(10) );
insert into test values( '' );
update test set val = ' ' where val = '';

更新确实会用空格替换空字符串,但where子句保持为true,并且update语句的重复执行会告诉您

(1 row(s) affected)

解决方法

Trailing blanks explained:

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.

这是上面提到的所有案例的一个众所周知的例子:

DECLARE @a VARCHAR(10)
DECLARE @b varchar(10)

SET @a = '1'
SET @b = '1 ' --with trailing blank

SELECT 1
WHERE 
    @a = @b 
AND @a NOT LIKE @b
AND @b LIKE @a

这是关于trailing blanks and the LIKE clause的更多细节.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读