,例如表a数据为: 列1 列2 1 a`b`c` 2 d`e`f`(换行符)g`h`l` 3 d`e`f`(换行符)g`h`l`(换行符)g``l` .. … 需要显示为: 列1 列2 列3 列4 1 a b c 2 d e f 2 g h l 3 d e f 3 g h l 3 g l 我用xml,先转化为xml,再按符号进行替换,再实现拆行和拆列,可是我在替换时,提示我查询出来的数据不止一条,不能跟多个。现在只能处理一条,怎么才能处理整个表呢,求高手 求一个能用的实例,谢谢,菜啊,sql server 2005/2008都可以,用视图或存储过程实现都可以
最新回答
墨染离殇
2022-05-17 00:08:03
什么数据库?
create table #(col1 int,col2 varchar(64)) go insert into # select 1,'a`b`c`' insert into # select 2,'d`e`f`'+char(13)+'g`h`l`' insert into # select 3,'d`e`f`'+char(13)+'g`h`l`'+char(13)+'g`l`' go
with cte1 as( select col1,tmp from ( select col1,xmlns = cast('<root><p>'+replace(col2,char(13),'</p><p>')+'</p></root>' as xml) from #)p cross apply ( select tmp=c.v.value('.','nvarchar(100)') from p.xmlns.nodes('/root/p')as c(v) )s ) select col1, col2 = left(tmp,1), col3 = left(stuff(tmp,1,2,''),1), col4 = left(stuff(tmp,1,4,''),1) from cte1 ---------结果 col1 col2 col3 col4 ----------- ---- ---- ---- 1 a b c 2 d e f 2 g h l 3 d e f 3 g h l 3 g l