Hi experts
I want to combine 15 columns alphabetically on a table and write them in another column, separated by commas. I currently do this with powershell and then write it to the sql database. But I suspect that this would be done much faster with a sql query.
Example:
column1 "D"
column2 "A"
column3 "C"
....etc
column15 "I"
drop table #Temp
create table #Temp ( col1 varchar(1) , col2 varchar(1) , col3 varchar(1))
insert into #Temp select 'B','A','C'
; with cte as
(
select * from (
select col1 as col1 from #temp
union all
select col2 from #temp
union all
select col3 from #temp
) a
order by col1
offset 0 rows
)
select STRING_AGG(col1,',') from cte
drop table if exists #Temp;
create table #Temp ( id int identity(1, 1) not null, col1 varchar(10) , col2 varchar(10) , col3 varchar(10), col4 varchar(10), col5 varchar(10), col6 varchar(10) );
insert into #Temp select 'B','A','C','F','L','I';
SELECT id, STUFF((SELECT ',' + CAST(col AS varchar(8000))
FROM ( VALUES(col1),(col2),(col3),(col4),(col5),(col6) ) AS cols(col)
ORDER BY col
FOR XML PATH(''), TYPE).value ('.', 'varchar(8000)'), 1, 1, '')
FROM #temp