splitting CSV string

Bandi
Posted by Bandi under Sql Server category on | Points: 40 | Views : 414
The below code splits the comma separated string into separate records...

DECLARE @Str NVARCHAR(MAX)
SET @Str = ',Str1,Str2,Str3,Str4,Str5,'
DECLARE @Part NVARCHAR(MAX)
DECLARE @IND INT
SET @IND = CHARINDEX(',',@Str)
DECLARE @EIND INT set @EIND = 0
WHILE(@IND != LEN(@STR))
BEGIN
SET @EIND = ISNULL(((CHARINDEX(',', @Str, @IND + 1)) - @IND - 1), 0)
-- Here you can insert the extracted words into a table variable ot temp table for further usage
SELECT (SUBSTRING(@Str, (@IND + 1), @EIND))
SELECT @IND = ISNULL(CHARINDEX(',', @STR, @IND + 1), 0)
END

Comments or Responses

Login to post response