当前位置: 代码迷 >> Sql Server >> 初学者,通过分隔符$$将一列分割成几列
  详细解决方案

初学者,通过分隔符$$将一列分割成几列

热度:9   发布时间:2016-04-24 09:19:52.0
菜鸟求助,通过分隔符$$将一列分割成几列
if object_id('tempdb..#WJ')>0
 drop table #WJ


select RANK() over (order by newid()) aid , te_title ,TE_Content into #wj from TE001 where  TE_Class=102

declare @t int,@maxt int, @p int
set @t=1
set @p=1
select @maxt=(COUNT(aid)) from #wj 
while @maxt>@t
begin
 declare @i int,@fld varchar(30),@fldc varchar(30),@str varchar(1000)
select @str =te_content from #wj where aid=@t
while @maxt>@p
SELECT @I=charindex('$$',@str) FROM #wj where  aid=@t
begin
while @i>=1
begin
set @fldc='F'+CAST (@p AS VARCHAR(8))
SET @fld='X'+CAST(@p AS VARCHAR(8))
 exec(' alter table #wj add '+@fldc+' VARCHAR(50) ')
   exec   ( ' alter table #wj add '+@fld+' VARCHAR(50) '  )
   exec ('UPDATE #wj SET '+@FLDC+'=a.b from (select substring(@str,1,@i)b from #wj where aid=@t)a ')
  end
     select @str=substring(@str,@i+1,LEN(@str)) from #wj where aid=@t 
 set @p=@p+1
  set @t=@t+1
 end 
end
select * from #wj




想要实现将Te_content通过分隔符$$分成几列。

------解决思路----------------------

if object_id('tempdb..#WJ')>0
 drop table #WJ


SELECT  RANK() OVER ( ORDER BY NEWID() ) aid
       ,te_title
       ,TE_Content --保留分拆前的值
       ,TE_Content2=TE_Content+'$$' --用于分拆判断
INTO    #wj
FROM    TE001
WHERE   TE_Class = 102


DECLARE @i VARCHAR(2)
SET @i='1'
WHILE EXISTS(SELECT 1 FROM #wj WHERE TE_Content2 LIKE '%$$%')
BEGIN
exec(' alter table #wj add [F'+@i+'] VARCHAR(50),[X'+@i+'] VARCHAR(50)')
EXEC('update #wj set [F'+@i+']=left(TE_Content2,CHARINDEX(''$$'',TE_Content2)-1) Where TE_Content2>''%$$%''')
UPDATE #wj SET TE_Content2=STUFF(TE_Content2,1,CHARINDEX('$$',TE_Content2)+1,'') WHERE TE_Content2 LIKE '%$$%'
END

SELECT * FROM #wj
  相关解决方案