我通读了documentation中的SqlServer EXCEPT运算符,但没有看到在字符串末尾显式修剪空白的内容。但是,在运行时:
SELECT 'Test'
EXCEPT
SELECT 'Test '
没有返回结果。任何人都可以解释这种行为,或者在使用EXCEPT时如何避免这种行为?
答案 0 :(得分:2)
ANSI SQL-92要求字符串在比较之前具有相同的长度,并且填充字符为空格。
在ANSI标准中(访问here的8.2节)
3)确定两个字符串的比较如下:
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 char- acters, where the pad character is chosen based on CS. If CS has the NO PAD attribute, then the pad character is an implementation-dependent character different from any char- acter in the character set of X and Y that collates less than any string under CS. Otherwise, the pad character is a <space>. b) The result of the comparison of X and Y is given by the col- lating sequence CS. c) Depending on the collating sequence, two strings may com- pare as equal even if they are of different lengths or con- tain different sequences of characters. When the operations MAX, MIN, DISTINCT, references to a grouping column, and the UNION, EXCEPT, and INTERSECT operators refer to character strings, the specific value selected by these operations from a set of such equal values is implementation-dependent.
如果必须避免这种情况,您可以将列作为EXCEPT的一部分反转:
SELECT 'TEST', REVERSE('TEST')
EXCEPT
SELECT 'TEST ', REVERSE('TEST ')
给出了预期的结果,但是很烦人,尤其是当您处理多个列时。
另一种选择是找到带有替代填充字符或无填充选项集的整理序列,尽管快速谷歌搜索后似乎在t-sql中不存在此序列。
或者,您可以用字符终止每一列,然后最后将其子字符串化:
SELECT SUBSTRING(col,1,LEN(col) -1) FROM
(
SELECT 'TEST' + '^' as col
EXCEPT
SELECT 'TEST ' + '^'
) results