SQL CTE to split a delimited string into a table

DECLARE @ListString varchar(8000)
SET @ListString = 'a,b,c,d'
DECLARE @List table (Item varchar(max))
 ;with cte (item, list) as
 (
 select cast('' as varchar(max)), @ListString
 union all
 select cast(left(list, charindex(',',list+',')-1) as varchar(max)) item,
 stuff(list, 1, charindex(',',list+','), '') list
 from cte where list <> ''
 )
 INSERT @List
 select item
 from cte
 where item <> ''

February 7, 2013 В· admin В· No Comments
Posted in: MSSQL, Tech

Leave a Reply