1. 程式人生 > >T-SQL行合並成列與列拆分成行

T-SQL行合並成列與列拆分成行

ont blank target where 感覺 一點 code returns bbb

原文:T-SQL行合並成列與列拆分成行

本文出處:http://www.cnblogs.com/wy123/p/6910468.html

  感覺最近sql也沒少寫,突然有一點生疏了,對於用的不是太頻繁的一些操作,時間一久就容易生。

多行的某一個列合並成一個列

CREATE TABLE TestColumnMergeAndSplit
(
    Id int Identity(1,1),
    BusinessId int,
    BusinessValue varchar(20)
)
GO



INSERT INTO TestColumnMergeAndSplit
SELECT 1,AAA UNION ALL SELECT 1,BBB UNION ALL SELECT 1,CCC UNION ALL SELECT 2,XXX UNION ALL SELECT 2,YYY UNION ALL SELECT 2,ZZZ GO SELECT * FROM TestColumnMergeAndSplit GO SELECT t1.BusinessId, STUFF ( ( SELECT ,+t2.BusinessValue
FROM TestColumnMergeAndSplit t2 WHERE t2.BusinessId = t1.BusinessId FOR XML PATH(‘‘) ), 1,1,‘‘ ) AS ColNames FROM TestColumnMergeAndSplit t1 GROUP BY t1.BusinessId GO

技術分享

  另外是一個相反的操作,借助上面合並之後的結果,將一個多個值的字符串列拆分開來,轉換為多行,

  技術分享

  用到的字符串拆分函數,比較常見

CREATE FUNCTION [dbo].[fn_SplitStringToTable] 
(
    @s     VARCHAR(max),
    @split VARCHAR(10)
)
RETURNS @re TABLE
        (
            Id INT IDENTITY(1,1),
            Value VARCHAR(100)
        )
AS
BEGIN

    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)
    RETURN
END

測試腳本,沒啥技術含量

CREATE TABLE TestColumnMergeAndSplit
(
    Id int Identity(1,1),
    BusinessId int,
    BusinessValue varchar(20)
)
GO

INSERT INTO TestColumnMergeAndSplit
SELECT 1,AAA
UNION ALL
SELECT 1,BBB
UNION ALL
SELECT 1,CCC
UNION ALL
SELECT 2,XXX
UNION ALL
SELECT 2,YYY
UNION ALL
SELECT 2,ZZZ
GO

SELECT * FROM TestColumnMergeAndSplit
GO
--合並多列為一列
SELECT  t1.BusinessId,
       STUFF
       (
            ( SELECT     ,+t2.BusinessValue 
              FROM      TestColumnMergeAndSplit t2
              WHERE     t2.BusinessId = t1.BusinessId
              FOR XML PATH(‘‘)
            ),
            1,1,‘‘
        )
         AS ColString
FROM   TestColumnMergeAndSplit t1
GROUP BY t1.BusinessId
GO

SELECT * FROM TestColumnMergeAndSplit_BAK
GO

SELECT t1.BusinessId,t1.ColString,t2.Id,t2.Value 
FROM TestColumnMergeAndSplit_BAK t1
    CROSS APPLY dbo.fn_SplitStringToTable(ColString,,)t2 
GO

  

T-SQL行合並成列與列拆分成行