Loop Through A Comma Delimited String In SQL

DECLARE @Items VARCHAR(1000)
SET @Items = ‘A,B,CD,E,FGH,KL,MNOP,QRSTU,V,W,XYZ’
DECLARE @Item VARCHAR(50)
DECLARE @Pos INT
DECLARE @Loop BIT
SELECT @Loop = CASE WHEN LEN(@Items) > 0 THEN 1 ELSE 0 END
WHILE (SELECT @Loop) = 1
BEGIN
SELECT @Pos = CHARINDEX(‘,’, @Items, 1)
IF @Pos > 0
BEGIN
SELECT @Item = SUBSTRING(@Items, 1, @Pos – 1)
SELECT @Items = SUBSTRING(@Items, @Pos + 1, LEN(@Items) – @Pos)
END
ELSE
BEGIN
SELECT @Item = @Items
SELECT @Loop = 0
END
END

Advertisements