1

Suppose I have a table like this with an undetermined number of comma-delimited values in one column:

thingID    personID

1          123,234,345

2          456,567

and I want to get it into a form like this:

thingID    personID

1          123

1          234

1          345

2          456

2          567

What is my best option for doing this? Oh I should mention the data is in a SQL 2008 R2 database so I may not be able to use the very latest functionality.

Greg
  • 13
  • 2
  • 1
    Take a peek at https://stackoverflow.com/questions/42796532/parsing-a-sql-field-in-a-query/42796923#42796923 Here, you have a option to use a UDF of In-line approach – John Cappelletti Jan 08 '18 at 19:42
  • I think your best bet would be with while/cursor. for each ```thingId``` split ```personId``` and insert it. also, consider checking other SO questions trying to achieve just that. – Ermir Beqiraj Jan 08 '18 at 19:43
  • 1
    @ErmirBeqiraj that's actually his worst bet. – Dave C Jan 08 '18 at 19:46
  • 1
    Read Aaron Bertrand's [Split strings the right way – or the next best way](https://sqlperformance.com/2012/07/t-sql-queries/split-strings) – Zohar Peled Jan 08 '18 at 19:50
  • @JiggsJedi agree that it's the last thing to consider, couldn't think of a set-based solution at the time(that's why comment not answer). I like the "Recursive method" answer from Racil. – Ermir Beqiraj Jan 09 '18 at 08:25

2 Answers2

0

Use CROSS APPLY with a string splitting function.
To find the string splitting function that works best for you, read Aaron Bertrand's Split strings the right way – or the next best way.

For this demonstration I've chosen to use the SplitStrings_XML function, simply because it's the first pure t-sql function in the article:

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

Now that we have a string splitting function, create and populate the sample table (Please save us this step in your future questions):

DECLARE @T AS TABLE
(
    thingID int,
    personID varchar(max)
)

INSERT INTO @T VALUES
(1, '123,234,345'),
(2, '456,567')

The query:

SELECT thingId, Item
FROM @T 
CROSS APPLY dbo.SplitStrings_XML(personID, ',')

Results:

thingId     Item
1           123
1           234
1           345
2           456
2           567

You can see a live demo on rextester.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

There are several ways to do that. Here are two methods for SQL Server 2008:

XML-Method: requires the string to allow for the xml-trick (no invalid XML chars)

SELECT a.thingID, Split.a.value('.', 'VARCHAR(100)') AS Data  
FROM (SELECT OtherID,  
             CAST('<M>' + REPLACE(personID, ',', '</M><M>') + '</M>' AS XML) AS Data  
      FROM table1) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

Recursive method:

;WITH tmp(thingID, DataItem, Data) AS (
    SELECT thingID, LEFT(personID, CHARINDEX(',', personID + ',') - 1),
        STUFF(personID, 1, CHARINDEX(',', personID + ','), '')
    FROM table1
    UNION ALL
    SELECT thingID, LEFT(personID, CHARINDEX(',', personID + ',') - 1),
        STUFF(personID, 1, CHARINDEX(',', personID + ','), '')
    FROM tmp
    WHERE Data > ''
)
SELECT thingID, DataItem AS personID
FROM tmp
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • Thanks for the response; I really appreciate your taking the time. All of these methods look useful and I have been able to acheive the goal – Greg Jan 09 '18 at 15:10