I have a table like this
Value String
-------------------
1 Cleo, Smith
I want to separate the comma delimited string into two colu
I think following function will work for you:
CREATE FUNCTION [dbo].[fn_split](
@str VARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE @pos INT
SELECT @str = @str + @delimiter
WHILE LEN(@str) > 0
BEGIN
SELECT @pos = CHARINDEX(@delimiter,@str)
IF @pos = 1
INSERT @returnTable (item)
VALUES (NULL)
ELSE
INSERT @returnTable (item)
VALUES (SUBSTRING(@str, 1, @pos-1))
SELECT @str = SUBSTRING(@str, @pos+1, LEN(@str)-@pos)
END
RETURN
END
You can call this function, like this:
select * from fn_split('1,24,5',',')
Declare @test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into @test
(ID, Data)
Values
('1','Cleo,Smith')
insert into @test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from @test