I have a string like this:
72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX
This is b
Create this SQL function:
CREATE FUNCTION [dbo].[StringSplit](@input NVARCHAR(MAX), @delimiter CHAR(1)=',')
RETURNS @returnTable TABLE(item NVARCHAR(100)) AS
BEGIN
IF @input IS NULL RETURN;
DECLARE @currentStartIndex INT, @currentEndIndex INT,@length INT;
SET @length=LEN(@input);
SET @currentStartIndex=1;
SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
WHILE (@currentEndIndex<>0)
BEGIN
INSERT INTO @returnTable VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @currentEndIndex-@currentStartIndex)))
SET @currentStartIndex=@currentEndIndex+1;
SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
END
IF (@currentStartIndex <= @length)
INSERT INTO @returnTable
VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @length-@currentStartIndex+1)));
RETURN;
END;
Usage example:
DECLARE @testString VARCHAR(100)
SET @testString = '72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX'
SELECT *
FROM [dbo].[StringSplit](@testString, DEFAULT)
Result (table):
72594206916
2
1/2/08
Tacoma
WA:72594221856
5
5/7/13
San Francisco
CA:72594221871
99
12/30/12
Dallas