Split CSV String into Table in SQL Server

Date April 5, 2010


By default there is no function in SQL Server that can split comma separated string into Table (Rows). Following t-sql is custom made function that can split csv string into table.

CREATE FUNCTION dbo.SplitCSV (@CSVString VARCHAR(8000), @Delimiter CHAR(1))
RETURNS @temptable TABLE (items VARCHAR(8000))
AS
BEGIN
	DECLARE @pos INT;
	DECLARE @slice VARCHAR(8000);

	SELECT @pos = 1;
	IF LEN(@CSVString) < 1 OR @CSVString IS NULL RETURN;

	WHILE @pos!= 0
	BEGIN
		SET @pos = CHARINDEX(@Delimiter,@CSVString);
		IF @pos != 0
			SET @slice = LEFT(@CSVString, @pos - 1);
		ELSE
			SET @slice = @CSVString;

		IF( LEN(@slice) > 0)
			INSERT INTO @temptable(Items) VALUES (@slice);

		SET @CSVString = RIGHT(@CSVString, LEN(@CSVString) - @pos);
		IF LEN(@CSVString) = 0 BREAK;
	END
	RETURN
END

Usage:

SELECT * FROM dbo.SplitCSV ('Computer,Keyboard,Mouse,USB', ',');

Related Posts

Tags: ,

PoorFairInterestingGoodExcellent (1 votes, average: 4.00 out of 5)
Loading ... Loading ...

4 Responses to “Split CSV String into Table in SQL Server”

  1. JoeDonahue.org » T-SQL Explode said:

    [...] push a set of CSV parameters into a temp table.  A slightly modified version of the function found here now allows me to do so! set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO /* select * from [...]

  2. dreambox 500s said:

    I m glad i found ur articles. Good post. thank you for sharing!

  3. Coleman Stigler said:

    This site seems to get a great deal of visitors. How do you get traffic to it? It gives a nice individual spin on things. I guess having something authentic or substantial to talk about is the most important thing.

  4. vishal said:

    This is great function and really usefull for me tnx dear

Leave a Reply

 

Most Rated Posts

Subscribe to Technology Tips

Subscribe to Saqib-Ansari via RSS

Or, subscribe via email: