Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The solution Madhivanan's link refers to is very creative, but I had a slight problem with it on SQL Server 2012 related to the name of one of the columns (Start). I've modified the code in his answer to use <code>StartPos</code> instead of <code>Start</code> for the column name.</p> <p>I was not familiar with the system procedure <code>spt_values</code>, but I found a very informative <a href="https://stackoverflow.com/questions/4273978/why-and-how-to-split-column-using-master-spt-values">description of the procedure here on SO</a> for those who are interested in exactly how this solution works.</p> <p>Finally, here's the (slightly) revised code from Madhivana's answer:</p> <pre><code>CREATE TABLE #test(id int, data varchar(100)) INSERT INTO #test VALUES (1,'This,is,a,test,string') INSERT INTO #test VALUES (2,'See,if,it,can,be,split,into,many,columns') DECLARE @pivot varchar(8000) DECLARE @select varchar(8000) SELECT @pivot = COALESCE(@pivot + ',', '') + '[col' + CAST(number + 1 AS VARCHAR(10)) + ']' FROM master..spt_values WHERE type = 'p' AND number &lt;= ( SELECT MAX(LEN(data) - LEN(REPLACE(data, ',', ''))) FROM #test ) SELECT @select = ' select p.* from ( select id,substring(data, StartPos+2, endPos-StartPos-2) as token, ''col''+cast(row_number() over(partition by id order by StartPos) as varchar(10)) as n from ( select id, data, n as StartPos, charindex('','',data,n+2) endPos from (select number as n from master..spt_values where type=''p'') num cross join ( select id, '','' + data +'','' as data from #test ) m where n &lt; len(data)-1 and substring(data,n+1,1) = '','') as data ) pvt Pivot ( max(token)for n in (' + @pivot + '))p' EXEC(@select) DROP TABLE #test </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload