Click here to Skip to main content
15,887,027 members
Articles / Programming Languages / T-SQL
Tip/Trick

Yet another string splitter

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
2 Oct 2011CPOL 7.6K  
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)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --