sqlServer 2008 一行转多行的问题怎么解决
如上图,需要将一行有逗号的转为多行,
这个问题是在cnblogs看到的
一看到这个问题
我的想法就是用游标实现
但发现有大神用sql xml实现了
果然高手
游标实现的代码量多且效率不高,xml的代码少,效率高
代码如下
-
create
table #table_temp( -
id
int identity(1,1) not null, -
txt
varchar(50)); -
declare
mycur cursor for select txt from Table_1 -
open
mycur -
declare
@t_txt varchar(50),@t_txt1 varchar(50) -
fetch
next from mycur into @t_txt -
while(@@FETCH_STATUS
= 0 ) -
begin
-
if
CHARINDEX(',',@t_txt)> 0 -
begin
-
0 ) -
-
@t_txt1 = substring(@t_txt,1,CHARINDEX(',',@t_txt)-1) -
#table_temp(txt) values(@t_txt1) -
@t_txt = SUBSTRING(@t_txt,CHARINDEX(',',@t_txt)+1,LEN(@t_txt) - LEN(@t_txt1)) -
-
into #table_temp(txt) values (@t_txt) -
end
-
else
-
begin
-
insert
#table_temp(txt) values(@t_txt) -
end
-
fetch
next from mycur into @t_txt -
end
-
close
mycur -
deallocate
mycur -
select
* from #table_temp -
drop
table
sql xml 实现方式如下
-
select
-
a.id,b.txt
-
from
-
(select
id,txt=convert(xml,''+replace(txt,',','')+'') from Table_1 -
)a
-
outer apply -
(select
txt=C.v.value('.','nvarchar(100)') from a.txt.nodes('/root/v')C(v))b