Recursive SQL to split CSV to table rows

本小妞迷上赌 提交于 2019-12-02 08:07:44

问题


After working on a different question here on SO, I stumbled across recursive CTEs which would on the surface seem a fairly easy way to solve the "Split a csv to table rows" problem.

I put this example together

DECLARE @InputString varchar(255) = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'

SELECT @InputString = @InputString + ','
;
with MyCTE(x,y)
as 
(
    SELECT 
        x = SUBSTRING(@InputString,0,PATINDEX('%,%',@InputString)),
        y = SUBSTRING(@InputString,PATINDEX('%,%',@InputString)+1,LEN(@InputString))
    UNION ALL
        SELECT 
            x = SUBSTRING(y,0,PATINDEX('%,%',y)),
            y = SUBSTRING(y,PATINDEX('%,%',y)+1,LEN(y))
        FROM 
            MyCTE 
        WHERE
                SUBSTRING(y,PATINDEX('%,%',y)+1,LEN(y)) <> '' OR 
            SUBSTRING(y,0,PATINDEX('%,%',y)) <> ''
)
SELECT x FROM MyCTE
OPTION (MAXRECURSION 2000);
GO

Is this really a bad idea? What is the overhead in SQL for recursive queries like this, and what are the potential pitfalls for this kind of approach.

Incidentally, I'm thinking this idea/technique could probably be leveraged to solve this other question.


回答1:


This one will work with empty strings

DECLARE @InputString VARCHAR(1000)
    SELECT @InputString = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,,1'

    SELECT SUBSTRING(',' + @InputString + ',', Number + 1,
    CHARINDEX(',', ',' + @InputString + ',', Number + 1) - Number -1)AS VALUE
    FROM master..spt_values
    WHERE type = 'p'
    AND Number <= LEN(',' + @InputString + ',') - 1
    AND SUBSTRING(',' + @InputString + ',', Number, 1) = ','
    GO

Also take a look at the comments here: Split string in SQL Server 2005+ CLR vs. T-SQL for some other ideas




回答2:


Though it's too late now and also the OP has an accepted answer, but still it's worth mentioning to read the article on Split Function in Sql Server using Set base approach where the author has shown many ways of achieving the same.



来源:https://stackoverflow.com/questions/5993201/recursive-sql-to-split-csv-to-table-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!