从逗号分隔的数据

时间:2017-09-07 20:55:37

标签: sql sql-server tsql

我有一个select语句以下列格式返回数据 - (来自糟糕的数据库设计)

ID  Numbers           
3   6,7,8    

我需要调整它才能返回

ID  Number             
3   6    
3   7  
3   8

修复它。最好的方法是什么?我不需要永久函数,我只需要从select查询中导出结果集即可导入新数据库。

谢谢!

2 个答案:

答案 0 :(得分:1)

由于您使用的是SQL Server 2015,因此最好的选择是编写如下的UDF:

CREATE FUNCTION [dbo].[udfSplit]
    (
      @sInputList VARCHAR(8000) -- List of delimited items
      ,
      @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
    )
RETURNS @List TABLE ( item VARCHAR(8000) )
    BEGIN
        DECLARE @sItem VARCHAR(8000);
        WHILE CHARINDEX(@sDelimiter, @sInputList, 0) <> 0
            BEGIN
                SELECT  @sItem = RTRIM(LTRIM(SUBSTRING(@sInputList, 1,
                                                       CHARINDEX(@sDelimiter,
                                                              @sInputList, 0)
                                                       - 1))) ,
                        @sInputList = RTRIM(LTRIM(SUBSTRING(@sInputList,
                                                            CHARINDEX(@sDelimiter,
                                                              @sInputList, 0)
                                                            + LEN(@sDelimiter),
                                                            LEN(@sInputList))));

                IF LEN(@sItem) > 0
                    INSERT  INTO @List
                            SELECT  @sItem;
            END;

        IF LEN(@sInputList) > 0
            INSERT  INTO @List
                    SELECT  @sInputList; -- Put the last item in
        RETURN;
    END;

并像这样使用它:

SELECT  ID ,
        item
FROM    ( SELECT    3 AS ID ,
                    '6,7,8' AS Numbers
        ) x
        CROSS APPLY udfSplit(x.Numbers, ',');

答案 1 :(得分:0)

试试这个:

DECLARE @YourTable Table (
    ID INT IDENTITY(1,1)
    , Number VARCHAR(10)
)
INSERT INTO @YourTable
VALUES
    ('1,2,3')
    , ('4,5,6,7')
    , ('8,9')
    , ('10')

;WITH CTE
AS
(
    SELECT 1 AS ID 
    UNION ALL
    SELECT ID + 1 FROM CTE
    WHERE ID < 100
)   
SELECT
    x.ID
    , SUBSTRING(x.Number, t.ID, CHARINDEX(',', x.Number + ',', t.ID) - t.ID) AS Number
FROM @YourTable x
JOIN CTE t
    ON t.ID <= DATALENGTH(x.Number)+1
    AND SUBSTRING(',' + x.Number, t.ID, 1) = ','
ORDER BY ID, Number

可在此处找到更多信息:http://www.sqlservercentral.com/articles/Tally+Table/72993/