Skip to content
Advertisement

Reverse to STRING_AGG

Here is a sample data on which we are further processing.

create table #tmp (id int identity(1,1), na varchar(10),me varchar(10))
insert into #tmp (na,me)
values 
('a','t'),
('a','u'),
('a','v'),
('a','w'),
('b','x'),
('b','y'),
('b','z')
select * from #tmp

My question is, is there any exact reverse of the STRING_AGG function for SQL Server?

Like I am merging using STRING_AGG with the following code

select na, STRING_AGG(me,',') as me into #tmp1 from #tmp group by na
select * from #tmp1

I need to reverse the process but I had to use CURSOR so I am searching for an alternative solution.

Below is the cursor code for better understanding the purpose.

declare @na varchar(10)
declare @me varchar(max)
create table #tmp3 (na varchar(10),me varchar(10))

declare dbc cursor for select na, me from #tmp1
open dbc

while 1=1
begin
    fetch next from dbc into @na, @me

    if @@FETCH_STATUS <> 0
        break;

    insert into #tmp3 (na,me)
    select @na, value
    from string_split(@me,',')
    
end

close dbc
deallocate dbc

select * from #tmp3

--Delete temp table

drop table #tmp
drop table #tmp1
drop table #tmp3

Advertisement

Answer

There is similar string_split is available which can be used, e.g.

for each string_agg using cross apply we can convert them back to rows,

select na,c.value
  from 
(select na, string_agg(me,',') as me
   from #tmp 
  group by na
) t
cross apply string_split(me, ',') c;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement