Jul 10, 2016

Handle comma separated string stored in a cell in SQL table

This is a challenging thing to do in SQL queries, though one single task that needs to be done in most of the instances. In other words, our challenge is to loop through the values stored in single cell.
My Sample string: Mango, Orange, Pine Apple, Avocado (Separator can be anything)


This is my first approach. PARSENAME is a special function we can use to retrieve item by item in string of items, but separator should be just “.” (i.e. dot). In fact, in my code I am first replacing my separator (which is “;”) to a dot.

Anyway, biggest drawback with this is, PARSNAME seems to be working only up to 4 items.

DECLARE @NumberOfItems int
DECLARE @Count int

SET @FruitStr = 'Mango;Orange;Pine Apple; Avocado'

SET @FruitStr = Replace(@FruitStr,';','.')
SET @NumberOfItems = (len(@FruitStr) - len(Replace(@FruitStr,'.','')))+1

SET @Count = 1

WHILE @Count <= @NumberOfItems
       PRINT PARSENAME(@FruitStr,@Count) --this is the single item
       SET @Count = @Count + 1;

2) For any number of items

This method works for any number of items. What I do here is identifying first item within a loop (by searching first separator) and looping through removing the item we already read.

SET @FruitStr = 'Mango;Orange;Pine Apple; Avocado'
SET @FruitStr = @FruitStr + ';'

WHILE CHARINDEX(';',@FruitStr,1) != 0
    SET @FruitItem = SUBSTRING(@FruitStr,1,CHARINDEX(';',@FruitStr,1))
    PRINT LEFT(@FruitItem,LEN(@FruitItem)-1) --this is the single item
    SET @FruitStr = SUBSTRING(@FruitStr,CHARINDEX(';',@FruitStr,1)+1,LEN(@FruitStr))

Hope this is helpful.

One practical usage I came through;

Once I needed this solution in Data migration for a CRM where source file for activities came with comma separated lists for Email addresses for Email activities or attendees of the Appointments. This way I managed to create JSON objects which were then injected through KingswaySoft Adaptor.