Get data between commas

Auerelio Vasquez
Auerelio Vasquez used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
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 VasquezETL Developer

Author

Commented:
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 VasquezETL Developer

Author

Commented:
Sorry I'd like the outcome to look like this

1 product1
1 product2
2 product3
2 product4
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Auerelio VasquezETL Developer

Author

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

So I want to solution to use the table and column name
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

Data Engineer
Commented:
/*
create table test1(id int, Products varchar(100))
insert into test1 values (1, 'Prod1, prod2, product3, prod4')
*/
SELECT id, ltrim(td.value('.', 'NVARCHAR(255)')) AS coverage
  FROM test1
CROSS APPLY (SELECT  CAST(('<td><![CDATA[' + REPLACE(Products, ',',']]></td><td><![CDATA[') + ']]></td>') AS XML) AS XmlData) ToXml
CROSS APPLY XmlData.nodes('td') A ( td );
/*
  	id	coverage
1	1	Prod1
2	1	prod2
3	1	product3
4	1	prod4
*/

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial