Split function equivalent in T-SQL?

后端 未结 15 1880
深忆病人
深忆病人 2020-11-21 07:23

I’m looking to split \'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15...\' (comma delimited) into a table or table variable.

Does anyone have a function that returns each one

15条回答
  •  一个人的身影
    2020-11-21 08:07

    This simple CTE will give what's needed:

    DECLARE @csv varchar(max) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15';
    --append comma to the list for CTE to work correctly
    SET @csv = @csv + ',';
    --remove double commas (empty entries)
    SET @csv = replace(@csv, ',,', ',');
    WITH CteCsv AS (
        SELECT CHARINDEX(',', @csv) idx, SUBSTRING(@csv, 1, CHARINDEX(',', @csv) - 1) [Value]
        UNION ALL
        SELECT CHARINDEX(',', @csv, idx + 1), SUBSTRING(@csv, idx + 1, CHARINDEX(',', @csv, idx + 1) - idx - 1) FROM CteCsv
        WHERE CHARINDEX(',', @csv, idx + 1) > 0
    )
    
    SELECT [Value] FROM CteCsv
    

提交回复
热议问题