Click here to Skip to main content
15,885,141 members
Articles / Database Development / SQL Server
Tip/Trick

Convert CSV list into a single column multiple rows

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
28 Mar 2011CPOL 13.5K   5   4
SQL
declare	@list nvarchar(max) = 'Imdad,Kuber,Maninder,Nirmal,Ajit';
declare	@Delimiter nvarchar(10) = ',';
DECLARE @LEN INT
SET @LEN=LEN(@List)+1

;With UserList AS
( 
	SELECT	
			cast(isNull(NULLIF(CHARINDEX(@Delimiter,@List,1),0),@LEN) as int) AS nEnd,
			RTRIM(LTRIM(SUBSTRING(@List,1,isNull(NULLIF(CHARINDEX(@Delimiter,@List,1),0),@LEN)-1))) AS Users
	UNION All
	SELECT	
			cast(isNull(NULLIF(CHARINDEX(@Delimiter,@List,nEnd+1),0),@LEN) as int),
			RTRIM(LTRIM(SUBSTRING(@List,nEnd+1,isNull(NULLIF(CHARINDEX(@Delimiter,@List,nEnd+1),0),@LEN)-nEnd-1)))
	FROM UserList
	WHERE nEnd<@LEN
)
SELECT NULLIF(Users,'') AS Users FROM UserList where 


--OUTPUT
--Users
---------
--Imdad
--Kuber
--Maninder
--Nirmal
--Ajit


Thanks,
Imdadhusen

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Infostretch Ahmedabad-Gujarat
India India
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen


AWARDS:

  1. 2nd Best Mobile Article of January 2015
  2. 3rd Best Web Dev Article of May 2014
  3. 2nd Best Asp.Net article of MAY 2011
  4. 1st Best Asp.Net article of SEP 2010


Read More Articles...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Savalia Manoj M7-Nov-12 1:13
Savalia Manoj M7-Nov-12 1:13 
GeneralRe: My vote of 5 Pin
Sunasara Imdadhusen22-Apr-14 4:03
professionalSunasara Imdadhusen22-Apr-14 4:03 
GeneralNice example. I usually just use the bcp.exe utility to impo... Pin
Keith.Badeau8-May-11 3:09
Keith.Badeau8-May-11 3:09 
GeneralRe: Nice example. I usually just use the bcp.exe utility to impo... Pin
Sunasara Imdadhusen22-Apr-14 4:03
professionalSunasara Imdadhusen22-Apr-14 4:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.