将逗号分隔值转换为行

时间:2014-04-01 16:34:42

标签: sql sql-server

我有一个场景,我必须将逗号分隔值转换为列。

实际值:

ID   NAME  Col1       Col2 
 1    A    AB,BC,CD     
 2    B                XY,YZ 
 3    C    DE,FE

预期:

ID  NAME   Col1       Col2 
 1   A      AB 
 1   A      BC 
 1   A      CD 
 2   B                 XY 
 2   B                 YZ 
 3   C      DE 
 3   C      EF 

以下是查询

SELECT a.ID,
       a.Name,
       b.splitdata ,
       c.splitdata
FROM dbo.TABLE1 a CROSS APPLY dbo.fnSplitString(a.COL1,',') AS b
CROSS APPLY dbo.fnSplitString(a.COL2,',') AS c

我得到结果为零。如果有人可以帮助我,请告诉我。

以下是拆分功能

ALTER FUNCTION [dbo].[fnSplitString]   
(   
    @string NVARCHAR(MAX),   
    @delimiter CHAR(1)   
)   
RETURNS @output TABLE(splitdata NVARCHAR(MAX)   
)   
BEGIN   
    DECLARE @start INT, @end INT   
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)   
    WHILE @start < LEN(@string) + 1 BEGIN   
        IF @end = 0    
            SET @end = LEN(@string) + 1  

        INSERT INTO @output (splitdata)    
        VALUES(SUBSTRING(@string, @start, @end - @start))   
        SET @start = @end + 1   
        SET @end = CHARINDEX(@delimiter, @string, @start)  

    END   
    RETURN   
END

1 个答案:

答案 0 :(得分:0)

很可能你的函数不处理NULL。

    SELECT a.ID,
           a.Name,
           b.splitdata ,
           c.splitdata
    FROM dbo.TABLE1 a 
    CROSS APPLY dbo.fnSplitString(isnull(a.COL1,'')',') AS b
    CROSS APPLY dbo.fnSplitString(isnull(a.COL2,''),',') AS c