Search

Monday, March 18, 2013

Split Comma-Separated Strings into Table

The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.SplitString(@String VarChar(8000), @Delimiter Char(1))
returns @TempTable TABLE (Data VarChar(8000))
AS
BEGIN
    DECLARE @iTemp Int
    DECLARE @Value VarChar(8000)

    SELECT @iTemp = 1       
        IF len(@String) < 1 or @String is null return

    WHILE @iTemp != 0
   BEGIN
   SET @iTemp = CharIndex(@Delimiter, @String)

       IF @iTemp != 0
       SET @Value = Left(@String, @iTemp - 1)
ELSE
SET @Value = @String

       IF (len(@Value) > 0)
       INSERT INTO @temptable(Data) Values(@Value)

       SET @String = Right(@String, len(@String) - @iTemp)
   IF len(@String) = 0 Break
END
return
END

Aboce function can be used as

SELECT TOP 5 * FROM dbo.SplitString('Lake Town,Bangur Avenue,Kestopur, Baguiati',',')  

No comments:

Post a Comment