2016-07-11 1 views
0
Table - tabtest 

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

Как для отображения значений, разделенных запятыми, какКак отображать значения таблицы SQL Server в Запятая Отделенные Значения

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] 

Пожалуйста, помогите

+0

Вы просто могли бы сделать кучу' ISNULL' заявлений ... например 'SELECT ISNULL (col1 + ',', '') + ISNULL (col2 + ',', '') + ISNULL (col3, '') [ConcatCols] FROM tblName' – ZLK

ответ

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) 

--This специально для трех колонок

;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 
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 

`

Смежные вопросы