首页 > 代码库 > 动态分行、动态分列(text数据类型的字段中,单元格包含分行字符)

动态分行、动态分列(text数据类型的字段中,单元格包含分行字符)

技术分享
--数据模拟请自行虚拟,本文为笔者使用需要从库中调取,为防止不必要的纠纷暂不提供数据IF OBJECT_ID(tempdb..#f)>0 DROP TABLE #fSELECT TOP 10 ROW_NUMBER()OVER(ORDER BY l.id) rid    ,l.id AS id    ,l.data_225 AS data_225    ,REPLACE(CAST(l.data_225 AS NVARCHAR(MAX)),CHAR(10),‘‘) AS data225INTO #f from openquery(mysql,SELECT * FROM flow_data_44 WHERE begin_time>=20150101;)lWHERE  CHARINDEX(CHAR(13),CAST(l.data_225 AS NVARCHAR(MAX)))>0--原始数据SELECT * FROM #fDECLARE @i INT ,@n INT ,@id INTDECLARE @tempdata VARCHAR(500)DECLARE @scr VARCHAR(max)SELECT @i=MIN(rid),@n=MAX(rid) FROM #f--动态分行IF OBJECT_ID(tempdb..#t)>0 DROP TABLE #t;CREATE TABLE #t(rid INT    ,id INT    ,data225 NVARCHAR(max)    ,data225di NVARCHAR(max))WHILE(@i<=@n)BEGIN    WHILE(EXISTS(SELECT 1 FROM #f WHERE ISNULL(data225,‘‘)<>‘‘ AND rid=@i))    BEGIN        SELECT @tempdata=SUBSTRING(a.data225,1, CHARINDEX(CHAR(13),a.data225))            ,@id=a.id        FROM #f a        WHERE rid=@i                INSERT INTO #t (rid,id,data225)         VALUES (@i,@id,@tempdata)                UPDATE #f SET data225=REPLACE(data225,@tempdata,‘‘) WHERE rid=@i            END    SET @i=@i+1END--分行结果SELECT * FROM #t--动态分列UPDATE #t SET data225di=REPLACE(REPLACE(data225,CHAR(10),‘‘),CHAR(13),‘‘)SET @i=1WHILE EXISTS(SELECT 1 FROM #t WHERE data225di<>‘‘)BEGIN    SET @scr=ALTER TABLE #t ADD col+CONVERT(VARCHAR,@I)+ VARCHAR(200)    EXEC(@scr)        SET @scr=declare @loc int update #t set @loc=charindex(‘‘`‘‘,data225di),col    +convert(varchar,@i)+=convert(varchar,case @loc when 0 then data225di else     +substring(data225di,1,@loc-1) end),data225di=case @loc when 0 then ‘‘‘‘ else     +substring(data225di,@loc+1,len(data225di)-@loc) end  where data225di<>‘‘‘‘‘        exec(@scr)    SET @i=@i+1ENDSELECT * FROM #t
代码请展开

效果图预览:

技术分享

动态分行、动态分列(text数据类型的字段中,单元格包含分行字符)