Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse XML data in SQL server table

I have SQL table:

Create table
(
ID varchar(50) not null,
Action nvarchar(max) null
)

Action column contains XML data. Format:

<?xml version="1.0" encoding="UTF-8"?> 
<oo_outbound_order>   
         <oo_master>
              <Code>123</Code>
              <Name>Branan</Name> 
    </oo_master> 
    </oo_outbound_order>

How to parse this column? Result should be like this:

CODE    NAME
123     Branan
like image 436
Kirill Rodeonov Avatar asked Sep 10 '18 10:09

Kirill Rodeonov


People also ask

How to put XML file in SQL Server database?

I have an XML file with a lot of data, and i want to put all that data in in SQL SERVER database, in a table with columns like the last exemple of the article. So, here is my code : GO EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML SELECT @XML = XMLData FROM XMLwithOpenXML

How to parse XML data in OLE DB?

In the Data Flow tab, drag and drop the following components and join them: Double click the OLE DB Source and connect to the table with the XML data type: Using the XML Parser Transform, select the input and write the XML String that you want to parse:

How to process XML data stored in a column in SQL?

Now as I said before, XML data stored in a column of data type XML can be processed either by using XML functions available in SQL Serveror by using thesp_xml_preparedocumentstored procedure along with the OPENXMLfunction.

How to change column type to XML in SQL Server?

Change the column type to XML by using the ALTER TABLE statement. You can bulk copy your data from another SQL Server database by using bcp out, and then bulk insert the data into the later version database by using bcp in.


2 Answers

Try the follwing meathod :

DECLARE @XMLData XML = '
<oo_outbound_order>   
    <oo_master>
        <Code>123</Code>
        <Name>Branan</Name> 
    </oo_master> 
</oo_outbound_order>'

SELECT
    [Code] = Node.Data.value('Code', 'INT'),
    [Name] = Node.Data.value('Name', 'NVARCHAR(20)')
    FROM @XMLData.nodes('/oo_outbound_order/oo_master') Node(Data)
like image 61
Jayasurya Satheesh Avatar answered Oct 07 '22 00:10

Jayasurya Satheesh


There are many tutorial articles about xml parsing with TSQL. For example, http://www.sqlserver.info/syntax/parse-xml-with-sql-server/

DECLARE @xml xml
SET @xml = 
'<?xml version="1.0" encoding="UTF-8"?> 
<oo_outbound_order>   
         <oo_master>
              <Code>123</Code>
              <Name>Branan</Name> 
    </oo_master> 
    </oo_outbound_order>'

SELECT 
    n.value('(./Code/text())[1]','int') as CODE
 , n.value('(./Name/text())[1]','Varchar(50)') as NAME
FROM @xml.nodes('/oo_outbound_order/oo_master') as a(n)
like image 27
vadzim dvorak Avatar answered Oct 07 '22 01:10

vadzim dvorak