Avatar of Auerelio Vasquez
Auerelio Vasquez
Flag for United States of America asked on

Get data between commas

Hi

I have data like this

Id        Products
1         Product1;product2

Separate by semi colon

I'd like the data like this

1 product1
1 product2

Etc
Microsoft SQL Server

Avatar of undefined
Last Comment
Sharath S

8/22/2022 - Mon
Shalu M

There are many ways you can do this depending on the version of SQL Server you're using.

SQL Server 2008 -

DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)
SET @str = 'product1;product2'
SET @delimiter = ';'
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml);

with data as (
SELECT '1' AS PRODUCT_ID, C.value('.', 'varchar(10)') as PRODUCT_NAME FROM @xml.nodes('X') as X(C)
)
select * from data;

Open in new window


Here's a reference - http://www.sqlservercentral.com/articles/XML/66932/

In SQL server 2016 there are inbuilt functions for splitting a string so you could try this code -

WITH DATA AS(
	SELECT '1' AS PRODUCT_ID, TRY_CAST(value AS VARCHAR) AS PRODUCT_NAME
	FROM   STRING_SPLIT ('product1;product2', ';') 
)
SELECT * FROM DATA;

Open in new window

Auerelio Vasquez

ASKER
This is a bit difficult to follow. Can you do it from the perspective that product is the column name and there may be more than one product in the column. Also Id is not always 1

It may be like this

ID        Products
1          Prod1, prod2, product3, prodn
2./
Auerelio Vasquez

ASKER
Sorry I'd like the outcome to look like this

1 product1
1 product2
2 product3
2 product4
Your help has saved me hundreds of hours of internet surfing.
fblack61
Auerelio Vasquez

ASKER
By the way products is a column in a table called events.

So I want to solution to use the table and column name
Nitin Sontakke

Hopefully you already have a script for a split function.

You can query it as follows:

select Id, s.data
from events e
outer apply dbo,split(e.Products, ',') s

Open in new window

ASKER CERTIFIED SOLUTION
Sharath S

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question