Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Por que SELECT DISTINCT a, b FROM... retorna menos registros que SELECT DISTINCT A + '|' + B DE...?


Espaços à direita podem causar isso. Para comparações de string, elas são ignoradas.
CREATE TABLE #T
(
a varchar(10),
b varchar(10),
c varchar(10)
)

INSERT INTO #T
SELECT 'a ' as a, 'b' as b, 'c ' as c union all
SELECT 'a' as a, 'b' as b, 'c ' as c

SELECT DISTINCT a, b, c  
FROM #T /*1 result*/

SELECT DISTINCT a + '|' + b + '|' + c + '|'   
FROM #T /*2 results*/


SELECT DISTINCT LTRIM(RTRIM(a)) + '|' + LTRIM(RTRIM(b)) + '|' +
                LTRIM(RTRIM(c)) + '|'   
FROM #T /*1 result*/