0

I have Input like this-

select ID,FIELD from TABLE

1| A,B,C,D
2|X,Y,Z

Output like this-

SELECT ID,FIELD from TABLE

1|A
1|B
1|C
1|D
2|X
2|Y
2|Z

Could someone please help me as how can I do it in SQL Server 2014 in an easy way ?

2 Answers2

1

You can choose a string splitting function from Aaron Bertrand's Split strings the right way – or the next best way, and use it with cross apply to select the data from your table. For this demonstration I've chosen to go with the XML string split function.
So first, create the function:

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

Then all you need to do is something like this:

SELECT ID, Item
FROM TABLE
CROSS APPLY
dbo.SplitStrings_XML(FIELD, ',')

See a live demo on rextester.

Also,you should probably read Is storing a delimited list in a database column really that bad?, where you will see a lot of reasons why the answer to this question is Absolutely yes!

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Thanks for the effort buddy but it din't work . Not sure why – Harsh Tiwari Sep 05 '17 at 22:37
  • What do you mean bit din't work? Did you get an error? did you get wrong results? [I've tested your sample data on rextester](http://rextester.com/DVPK21692) and it seems to me it's working just fine. – Zohar Peled Sep 06 '17 at 05:17
0

You should XML With CROSS APPLY no need Explicit Function :

SELECT ID,
       split.a.value('.', 'NVARCHAR(MAX)') [FIELD]
FROM
(
    SELECT ID,
           CAST('<M>'+REPLACE([Field], ',', '</M><M>')+'</M>' AS XML) AS String
    FROM #TM
) AS a
CROSS APPLY String.nodes('/M') AS split(a);

Result :

ID FIELD
1  A
1  B
1  C
1  D
2  X
2  Y
2  Z
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52