Search code examples
sqlexcelsplitsubtractiondelimited

How to subtract from each number in a comma delimited string?


I have a table with a string field where than can be one number or mulitple numbers (delimited by a comma). I need to find the difference between the values (when converted to an integer) and an unspecified value. For simplicity sake for this question, I'll just say the value to be compared is a static value of 10.

Example Table:

iId vchStringNumbers vchSubtractedStringNumbers 1 20, 30, 40 2 50 3 20

Desired Results:

iId vchStringNumbers vchSubtractedStringNumbers 1 20, 30, 40 10, 20, 30 2 50 40 3 20 10

Is there a way to accomplish this in SQL? If it would be eaiser in excel or something like that, feel free to answer as well.


Solution

  • Place you CS data in an Excel column, Select the cells and run this tiny VBA macro:

    Sub SubtractCSV()
        Dim r As Range
        For Each r In Selection
            ary = Split(r.Value, ",")
            For i = LBound(ary) To UBound(ary)
                ary(i) = CLng(Trim(ary(i))) - 10
            Next i
            r.Offset(0, 1).Value = Join(ary, ",")
        Next r
    End Sub