Pages

Tuesday, May 26, 2009

Convert list of values seperated by comma stored in a column into Multiple Rows in SQL Server

Today, I would like to give you simple tip to convert list of values seperated by comma stored in a column into Multiple Rows in SQL Server.

-- Create Numbers Table
Create table Numbers(num Int Not Null);
alter table Numbers add constraint pk_Numbers primary key clustered(num);


-- Populate Numbers table
INSERT INTO numbers
SELECT number FROM master..spt_values WHERE type = 'P';

-- Declare the variable and Run the Actual Query to convert Columns to Rows
declare @String varchar(MAX)
set @String = '100,200,250,300,350,450,500'
set @String =','+ @String + ','
SELECT REPLACE(Val_Column,',','')
FROM
(
select
substring(@String,Num,CHARINDEX(',',@String,Num+1)-Num) As Val_Column
from
Numbers
where num < LEN(@String)
) C
where Val_Column like ',%'

No comments: