use convert to XML
and cross apply
:
DECLARE @str varchar(50)
SET @str='John, Samantha, Bob, Tom'
SELECT names = y.i.value('(./text())[1]', 'nvarchar(1000)')
FROM
(
SELECT
n = CONVERT(XML, '<i>'
+ REPLACE(@str, ',' , '</i><i>')
+ '</i>')
) AS a
CROSS APPLY n.nodes('i') AS y(i)
OUTPUT:
names
-----
John
Samantha
Bob
Tom
EDIT: it's not need to the temp table inside the proc so the proc will be:
CREATE PROCEDURE myProc
(@nameList varchar(500))
AS
BEGIN
SELECT names = y.i.value('(./text())[1]', 'nvarchar(1000)')
FROM
(
SELECT
n = CONVERT(XML, '<i>'
+ REPLACE(@nameList, ',' , '</i><i>')
+ '</i>')
) AS a
CROSS APPLY n.nodes('i') AS y(i)
END
but if you want to insert it into a temp table, below is a the sample:
create table #names
(
Name varchar(20)
)
DECLARE @str varchar(50)
SET @str='John, Samantha, Bob, Tom'
insert into #names
SELECT names = y.i.value('(./text())[1]', 'nvarchar(1000)')
FROM
(
SELECT
n = CONVERT(XML, '<i>'
+ REPLACE(@str, ',' , '</i><i>')
+ '</i>')
) AS a
CROSS APPLY n.nodes('i') AS y(i)
select * from #names
drop table #names
EDIT 2: the input string may contains some special characters like '<' , '>' , etc
it's not standard for names but if the the given string contains them you can remove them by using replace
function : replace(@str,'<','')