Programming, SQL Database

Split Comma Separated List Without Using a Function

There is lots way to get the table from comma separate data by using the function to return table but I found the other way using XML path and using this you get better performance than another way while there are lots of data in a table. Even you get more time using function while to join with other tables so you can consider following example and fit your need and definitely you would get better performance and could enhance your query.

Table: ProductGroup

SELECT GroupID,ProductCode FROM ProductGroup

GroupID     ProductCode
1                 GH0001,MH0001,GH0002
2                 GH0003,MH067
3                 GH0004,MH0002,MH0670

Now we can get result by run following query to get each ProductCode separately with GroupID as below:

LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Code
SELECT GroupID,CAST('' + REPLACE(Code,',','') + '' AS XML) AS x
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n) 

Result that you want as below:

GroupID     Code
1               GH0001
1               MH0001
1               GH0002
2               GH0003
2               MH067
3               GH0004
3               MH0002
3               MH0670

So finally the result with separate ProductCode with associated GroupID and now you can use this trick to join with other table to compare record by each ProductCode.


Leave a Reply

Your email address will not be published. Required fields are marked *