Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split more than one comma separated column as a separate row in SQL using CROSS APPLY

I have one table having following rows

Name Phones Courses
ABC 123, 456 HTML, Java
XYZ 321, 654 PHP, CSS

now I want to write a SELECT query to get these comma separated Phone and Courses as a separate row. By using this SELECT query I yield results till Phone column but stuck at 2nd column. Select query is

SELECT 
    Name, 
    value phone,
    courses
FROM 
    tblName 
    CROSS APPLY STRING_SPLIT(phones, ',');

This query shows me following results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name Phones Courses
ABC 123 HTML, Java
ABC 456 HTML, Java
XYZ 321 PHP, CSS
XYZ 654 PHP, CSS

Please help me to split Courses column as like Phones and want to yield following results:

Name Phones Courses
ABC 123 HTML
ABC 456 HTML
ABC 123 Java
ABC 456 Java
XYZ 321 PHP
XYZ 654 PHP
XYZ 321 CSS
XYZ 654 CSS

>Solution :

Since – according to your description – you used CROSS APPLY and your query was successfully executed, this means you are using a SQL Server DB, not MY SQL. You can do two CROSS APPLY to get your expected result. This will produce exactly the outcome you have shown in your question:

SELECT name, phone, value courses FROM
(SELECT name, value phone, courses 
FROM tblName CROSS APPLY STRING_SPLIT(phones, ',')) x
CROSS APPLY STRING_SPLIT(courses, ',')
ORDER BY name, courses, phone;

You can verify this here: db<>fiddle

But this is very risky and you really should avoid such comma-separated contents in one column. I highly recommend to create separate columns for the different values in future.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading