Tuesday, February 10, 2015

Seperate the Unique String value into multiple with comma seperator

I have a requirement saying I want to pass a string as parameter and should get the results by splitting string by each Comma(,) and load them in to a table
/*                   CODE HERE

SET NOCOUNT ON

DECLARE @MyTask TABLE (Result VARCHAR(25))
DECLARE @String VARCHAR(500) = 'SQL,Oracle,MySQL,DB2,NoSQL'
DECLARE @SplitValues VARCHAR(25)

WHILE LEN(@String) > 0
BEGIN
    IF PATINDEX('%,%',@String) > 0
    BEGIN
        SET @SplitValues = SUBSTRING(@String, 0, PATINDEX('%,%',@String))
        INSERT INTO @MyTask
            SELECT @SplitValues

        SET @String = SUBSTRING(@String, LEN(@SplitValues + ',') + 1,LEN(@String))
    END
    ELSE
    BEGIN
        SET @SplitValues = @String
        SET @String = NULL
        INSERT INTO @MyTask
            SELECT @SplitValues
    END
END
SELECT * FROM @MyTask

*/
You may pass the parameter(Unique string) with any kind of Separator. You should be make sure with it during the implementation.