如何在逗号分隔值中显示SQL Server表值

时间:2016-07-11 04:54:40

标签: sql sql-server

Table - tabtest

Col1 Col2 Col3
abc  NULL xyz
NULL NULL mno
NULL pqr  stuv
def  lmn  NULL

如何显示逗号分隔值,如

OUTPUTX
abc,xyz
mno
pqr,stuv
def,lmn

下面是我的查询,显示正确,但如果单元格值包含逗号,则表示错误

SELECT REPLACE(REPLACE(REPLACE(ISNULL(LTRIM(RTRIM(col1)),' ')+',' + ISNULL(LTRIM(RTRIM(col2)),' ')+ ','+ISNULL(LTRIM(RTRIM(col3)),' '),',,',','),' ,',''),', ','') outputx from [tabtest]

请帮忙

3 个答案:

答案 0 :(得分:2)

Demo Here

这适用于N列:

;With cte
as
(select 
*,row_number() over (order by (select null)) as rn from t1
)
select stuff(b.t,1,1,'')  from cte
cross apply
(select ','+v
from
(values(col1),(col2),(col3)) b(v)
for xml path(''))b(t)

- 这是专门针对三列的

 ;With cte
    as
    (
        select 
        col1+',' as col1,
        case when col3 is null or col2 is null 
             then col2 else col2+',' 
        end as col2,
        col3 as col3
        from t1
    )
    Select CONCAT(col1,col2,col3) from cte

如果没有空值,您可以简单地执行

 select CONCAT(col1,','col2,',',col3) from table

答案 1 :(得分:0)

解决方案1 SELECT ISNULL(col1 + ',', '') + ISNULL(col2 + ',', '') + ISNULL(col3, '')

解决方案2 look here

change this

答案 2 :(得分:0)

`select 
 case
 when col1 is not null and col2 is null and col3 is null then col1
 when col1 is null and col2 is not null and col3 is null then col2
 when col1 is null and col2 is null and col3 is not null then col3
 when col1 is not null and col2 is not null and col3 is null then col1+','+col2
 when col1 is not null and col2 is null and col3 is not null then col1+','+col3
 when col1 is null and col2 is not null and col3 is not null then col2+','+col3
 when col1 is not null and col2 is not null and col3 is not null then col1+','+col2+','+col3 
 else cast(null as varchar(50)) end OUTPUTX
 from tabtest2

`