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

谁能解释原因
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的更多细节.

相关文章

(一)日志传送架构 (1.1)相关服务器 主服务器 :用于生产的服务器,上面运行这生产SQL Server数据库...
(一)事故背景 最近在SQL Server 2012生产数据库上配置完事物复制(发布订阅)后,生产数据库业务出现了...
(一)测试目的 目前公司使用的SQL SERVER 2012高可用环境为主备模式,其中主库可执行读写操作,备库既...
(一)背景个人在使用sql server时,用到了sql server的发布订阅来做主从同步,类似MySQL的异步复制。在...
UNION和OR谓词 找出 product 和 product2 中售价高于 500 的商品的基本信息. select * from product wh...
datawhale组队学习task03