Varchar 等式在 SQL 表达式中如何工作?

How does Varchar equality work in SQL expressions?

varchar 等式在 SQL 中如何工作,为什么? '1'实际上不同于'1'。查看右侧操作数中的空格:

SELECT CASE 
       WHEN '1' = '1    ' THEN 'yes'
       ELSE 'no'
       END
-- results in yes

输出是'yes',但为什么?

您正在比较两个字符串。当一个字符串有空格时,它是不同的。
您可以使用 REPLACE('1 ', ' ', '').

删除所有空格

两个字符串 '1' 和 '1' 不相等导致 space .. 为避免这种情况,您应该使用 trim

SELECT CASE 
          WHEN trim( '1' ) =  trim('1    ' ) THEN 'yes'
          ELSE 'no'
       END 

SQL 将在比较 =,>,<,>=,<= 运算符上的 varchar 值时忽略所有尾随空格。

如果您比较“1”和“1”,则结果为 false。但是 '1' 和 '1' 为真。

; with cte as (
SELECT ' 1' as a, '1' as b )
select case when a= b then 'dd' else 'ff' end from cte

Result
--------
ff


; with cte as (
SELECT '1 ' as a, '1' as b )    
select case when a= b then 'dd' else 'ff' end from cte

Result
------
dd


种类sql内部默认执行RTRIM

您可能会找到此 link 以获取更多信息 LINK

此行为符合规范。来自 very old version of specs:

3) The comparison of two character strings is determined as follows:

a) If the length in characters of X is not equal to the length in characters of Y, then the shorter string is effectively replaced, for the purposes of comparison, with a copy of itself that has been extended to the length of the longer string by concatenation on the right of one or more pad characters, where the pad character is chosen based on CS. [...] Otherwise, the pad character is a <space>.

用简单的英语来说,是的,11 ​ 比较相等,但 1​ 1 不相等。