So here is the starting point
CREATE TABLE #Data (
ID INT IDENTITY(1,1),
MyData VARCHAR(200)
)
INSERT INTO #Data (Data) VALUES ('Test123, Test678')
INSERT INTO #Data (Data) VALUES ( 'abcd, efgh, mnop')
I want to parse comma separated data from MyData column and associate it back to related ID. So the final result will be
ID ParsedData
--------------
1 Test123
1 Test678
2 abcd
2 efgh
2 mnop
I can do it via cursors but want to avoid it. Is there any better way of writing query for it?
The optimum way of doing this is the subject of much controversy and also depends on the length of the string, frequency of the delimiters, concurrent usage, suitability in parallel plans, whether the results will be used in a JOIN operation...
Erland Sommarskog does some performance tests here.
I've linked to Adam Machanic's TSQL split function below that uses a numbers table. There are a load more in the link above.
1. Create a numbers table
2. Create a split function
SELECT ID,OutParam
FROM #Data
CROSS APPLY dbo.SplitString(MyData,',')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With