Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 反转为字符串_AGG_Sql_Sql Server_Split_Cursor_String Agg - Fatal编程技术网

Sql 反转为字符串_AGG

Sql 反转为字符串_AGG,sql,sql-server,split,cursor,string-agg,Sql,Sql Server,Split,Cursor,String Agg,这是我们正在进一步处理的样本数据 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 我的问题是,SQL Server的STRING_AGG函数是否有

这是我们正在进一步处理的样本数据

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
我的问题是,SQL Server的STRING_AGG函数是否有完全相反的形式

就像我正在使用STRING_AGG与下面的代码合并一样

select na, STRING_AGG(me,',') as me into #tmp1 from #tmp group by na
select * from #tmp1
我需要反转这个过程,但我必须使用游标,所以我正在寻找替代解决方案

下面是光标代码,以便更好地理解其用途

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
有类似的字符串可供使用,例如

对于使用交叉应用的每个字符串,我们可以将它们转换回行

select na,c.value
  from 
(select na, string_agg(me,',') as me
   from #tmp 
  group by na
) t
cross apply string_split(me, ',') c;
string_split不是一个精确的倒数,因为它不能保证保持顺序。所以,这取决于你想做什么。