How To Split A Comma Delimited String


How To Split A Comma Delimited String

In one of my previous posts I wrote about “How to Create a Comma Delimited List”.  Now I’ll show you an example with reverse action, that is Splitting a Comma Delimited String or array() of values.
There can be different types of Delimiters also : like Comma ' , ', vertical bar ' | ', Single space or a Tab.
For example here is our Sample Table -
IdAllNames
1A,B,C
2A,B
3X,Y,Z
And here is the expected output -
IdNames
1A
1B
1C
2A
2B
3X
3Y
3Z
Create Sample Data :
-- Create Table for  Sample Data
CREATE TABLE Test
(
ID INT,
AllNames VARCHAR(100)
)
GO
-- Load Sample Data INSERT INTO test SELECT
1, 'A,B,C' UNION ALL SELECT
2, 'A,B'  UNION ALL SELECT
3, 'X,Y,Z'
GO

-- Verify the Sample Data
SELECT Id, AllNames
FROM Test
And here is the query for How to split a comma delimited string :
;WITH Cte AS
(
    SELECT
        id,
        CAST('<M>' + REPLACE( Allnames,  ',' , '</M><M>') + '</M>' AS XMLAS Names
    FROM Test
)
SELECT
    ID,
    Split.a.value('.''VARCHAR(100)'AS Names
FROM Cte
CROSS APPLY Names.nodes('/M') Split(a)

Comments

Popular posts from this blog

MOLAP, ROLAP, And HOLAP

Difference Between CURRENT_TIMESTAMP and GETDATE()

Convert Seconds to HH:MM:SS