首页 > 代码库 > T-SQL行合并成列与列拆分成行
T-SQL行合并成列与列拆分成行
本文出处:http://www.cnblogs.com/wy123/p/6910468.html
感觉最近sql也没少写,突然有一点生疏了,对于用的不是太频繁的一些操作,时间一久就容易生。
多行的某一个列合并成一个列
CREATE TABLE TestColumnMergeAndSplit( Id int Identity(1,1), BusinessId int, BusinessValue varchar(20))GOINSERT INTO TestColumnMergeAndSplitSELECT 1,‘AAA‘UNION ALLSELECT 1,‘BBB‘UNION ALLSELECT 1,‘CCC‘UNION ALLSELECT 2,‘XXX‘UNION ALLSELECT 2,‘YYY‘UNION ALLSELECT 2,‘ZZZ‘GOSELECT * FROM TestColumnMergeAndSplitGOSELECT t1.BusinessId, STUFF ( ( SELECT ‘,‘+t2.BusinessValue FROM TestColumnMergeAndSplit t2 WHERE t2.BusinessId = t1.BusinessId FOR XML PATH(‘‘) ), 1,1,‘‘ ) AS ColNamesFROM TestColumnMergeAndSplit t1GROUP BY t1.BusinessIdGO
另外是一个相反的操作,借助上面合并之后的结果,将一个多个值的字符串列拆分开来,转换为多行,
用到的字符串拆分函数,比较常见
CREATE FUNCTION [dbo].[fn_SplitStringToTable] ( @s VARCHAR(max), @split VARCHAR(10))RETURNS @re TABLE ( Id INT IDENTITY(1,1), Value VARCHAR(100) )ASBEGIN IF @s IS NULL RETURN IF @split IS NULL RETURN IF(LEN(@split)<=0) BEGIN INSERT INTO @re VALUES (@s) RETURN END DECLARE @splitlen INT SET @splitlen=LEN(@split ) - 1 WHILE CHARINDEX(@split, @s) > 0 BEGIN INSERT @re VALUES(LEFT(@s, CHARINDEX(@split, @s) - 1)) SET @s=STUFF(@s, 1, CHARINDEX(@split, @s) + @splitlen, ‘‘) END INSERT @re VALUES(@s) RETURNEND
测试脚本,没啥技术含量
CREATE TABLE TestColumnMergeAndSplit( Id int Identity(1,1), BusinessId int, BusinessValue varchar(20))GOINSERT INTO TestColumnMergeAndSplitSELECT 1,‘AAA‘UNION ALLSELECT 1,‘BBB‘UNION ALLSELECT 1,‘CCC‘UNION ALLSELECT 2,‘XXX‘UNION ALLSELECT 2,‘YYY‘UNION ALLSELECT 2,‘ZZZ‘GOSELECT * FROM TestColumnMergeAndSplitGO--合并多列为一列SELECT t1.BusinessId, STUFF ( ( SELECT ‘,‘+t2.BusinessValue FROM TestColumnMergeAndSplit t2 WHERE t2.BusinessId = t1.BusinessId FOR XML PATH(‘‘) ), 1,1,‘‘ ) AS ColStringFROM TestColumnMergeAndSplit t1GROUP BY t1.BusinessIdGOSELECT * FROM TestColumnMergeAndSplit_BAKGOSELECT t1.BusinessId,t1.ColString,t2.Id,t2.Value FROM TestColumnMergeAndSplit_BAK t1 CROSS APPLY dbo.fn_SplitStringToTable(ColString,‘,‘)t2 GO
T-SQL行合并成列与列拆分成行
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。