Menu Close

TSQL – Split Comma Delimited String

If you are trying to split a comma delimited string there are number of option to do that. One of the easiest ways is to use XML. Be careful if you use XML because it can only be used if you can guarantee that your input string does not contain any illegal XML characters (i.e. <, > or &).

Lets say you have a table like this:

ID | ColumnToSplit
CD315A97-7ACB-44E2-8338-86A1071BC123 | Some Value, Another Value, BlaBla/Bla
D4CB2652-8BFE-449F-A4CD-9C274CD9D358 | Something, Other Value, Some Value

The following code:

SELECT A.ID
, Split.a.value(‘.’, ‘VARCHAR(100)’) AS [Split_Value]

FROM
(
SELECT r.ID
, CAST (‘‘ + REPLACE(r.ColumnToSplit, ‘, ‘, ‘‘) + ‘‘ AS XML) AS [Data]

FROM YourTable as r

) AS A CROSS APPLY Data.nodes (‘/M’) AS Split(a)

Will do the following:

ID | Split_Value
CD315A97-7ACB-44E2-8338-86A1071BC123 | Some Value
CD315A97-7ACB-44E2-8338-86A1071BC123 | Another Value
CD315A97-7ACB-44E2-8338-86A1071BC123 | BlaBla/Bla
D4CB2652-8BFE-449F-A4CD-9C274CD9D358 | Something
D4CB2652-8BFE-449F-A4CD-9C274CD9D358 | Other Value
D4CB2652-8BFE-449F-A4CD-9C274CD9D358 | Some Value

For more on that topic and other methods check this link:
http://sqlperformance.com/2012/07/t-sql-queries/split-strings