You can use a very simple technique to split string
s using T-SQL. No more while
loops.
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:
select * from dbo.SplitValues('abc,def,ghi,klm', ',')