Split function equivalent in T-SQL?

后端 未结 15 1827
深忆病人
深忆病人 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

    I am tempted to squeeze in my favourite solution. The resulting table will consist of 2 columns: PosIdx for position of the found integer; and Value in integer.

    
    create function FnSplitToTableInt
    (
        @param nvarchar(4000)
    )
    returns table as
    return
        with Numbers(Number) as 
        (
            select 1 
            union all 
            select Number + 1 from Numbers where Number < 4000
        ),
        Found as
        (
            select 
                Number as PosIdx,
                convert(int, ltrim(rtrim(convert(nvarchar(4000), 
                    substring(@param, Number, 
                    charindex(N',' collate Latin1_General_BIN, 
                    @param + N',', Number) - Number))))) as Value
            from   
                Numbers 
            where  
                Number <= len(@param)
            and substring(N',' + @param, Number, 1) = N',' collate Latin1_General_BIN
        )
        select 
            PosIdx, 
            case when isnumeric(Value) = 1 
                then convert(int, Value) 
                else convert(int, null) end as Value 
        from 
            Found
    

    It works by using recursive CTE as the list of positions, from 1 to 100 by default. If you need to work with string longer than 100, simply call this function using 'option (maxrecursion 4000)' like the following:

    
    select * from FnSplitToTableInt
    (
        '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' + 
        '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
        '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
        '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
        '9, 8, 7, 6, 5, 4, 3, 2, 1, 0'
    ) 
    option (maxrecursion 4000)
    

提交回复
热议问题