Sunday, December 16, 2018

How to Split the Comma Separated Values from a Column into Multiple Rows in SQL Server

How to use XML Method to Split the Comma Separated Values from a Column into Multiple Rows in SQL Server
Suppose the Source Table as follows..

DECLARE @csvData TABLE
                           (
                              EmpID INT,
                              Qalifi VARCHAR(4000)
                            )

Insert into @csvData Values(1,'B.E.,123.45, MBA, 986.54'), (2,'M.Com.,45.67'), (3,'M.Sc.,M.Tech.')
Select * From @csvData
GO

In the above Table(@csvData) , in the Column 'Qualfi' we have the Comma Separated Values. Now we can convert and separate those values in multiple rows using the below Query with XML Method.
DECLARE @csvData TABLE
(
EmpID INT,
Qalifi VARCHAR(8000)
)

Insert into @csvData Values(1,'B.E.,123.45, MBA, 986.54'), (2,'M.Com.,45.67'), (3,'M.Sc.,M.Tech.')
Select * From @csvData


Select EmpID,
LTRIM(RTRIM(m.n.value('.[1]','varchar(4000)'))) As Qalifi
From
(
Select EmpID, CAST( ( '<XMLRoot><RowData>' +

                                       REPLACE(Qalifi,',','</RowData><RowData>') + 
                                      '</RowData></XMLRoot>' ) As XML
                                 ) As X
From   @csvData
) T1

CROSS APPLY X.nodes('/XMLRoot/RowData')m(n)
GO
Notes:
In the above Query, we can use any letters instead of m, n.
Output:

Note:
The above query can written as per below as well.
Select EmpID, LTRIM(RTRIM([i].value('.','varchar(4000)'))) As Qalifi
From
        (
           Select EmpID, CAST( ( '<root><i>' +
                                                 REPLACE(Qalifi,',','</i><i>') +
                                                 '</i></root>' ) As XML
                                                ) As X
           From @csvData
         ) T1
CROSS APPLY X.nodes('/root/i') As [Items]([i])
GO

--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog