Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / T-SQL

Yet another string splitter

5.00/5 (1 vote)
2 Oct 2011CPOL 7.7K  
Splits string using TSQL, but a very simple technique using the XML datatype.

You can use a very simple technique to split strings using T-SQL. No more while loops.


SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION dbo.SplitValues
(	
	@str			varchar(300),
	@demiliter		char(1)
)
RETURNS @TblList	table 	
(	val		varchar(20) )
AS
BEGIN 

	declare @xml xml
	SELECT @xml = CONVERT(xml,'<root><s>' + 
           REPLACE(@str, @demiliter,'</s><s>') + 
           '</s></root>')
	insert into @TblList
	select T.c.value('.','varchar(20)')
	FROM @xml.nodes('/root/s') T(c)
	return
END
GO

Test the function like this:


SQL
select * from dbo.SplitValues('abc,def,ghi,klm', ',')

License

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