Recursive SQL to split CSV to table rows

后端 未结 2 1426

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\" p

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 06:08

    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

提交回复
热议问题