Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server XML parse issue

Tags:

sql-server

xml

I need to parse XML into a SQL Server 2012 database. However, I cannot find any good guide to parse this kind XML (here is SELECT TOP 2 FROM table):

<ns2:SoftWare xmlns:ns2="http://www.example.com" xmlns:ns3="http://www.example2.com"><keyc>123-ABC</keyc><statusc>Y</statusc></ns2:SoftWare>
<ns2:custom-data xmlns:ns2="http://www.example.com/2"><timec>2016.01.02</timec><customer>8R</customer><keyc>8R</keyc><statusc>N</statusc></ns2:custom-data>

Any help, how I can parse "keyc" value from XML?

So, I can use it select clause / or insert it to database.

like image 603
Dillaccithe Avatar asked Feb 26 '26 07:02

Dillaccithe


1 Answers

You can use the nodes and value to get that entity:

DECLARE @Data TABLE (XmlText XML)
INSERT @Data VALUES
    ('<ns2:SoftWare xmlns:ns2="http://www.example.com" xmlns:ns3="http://www.example2.com"><keyc>123-ABC</keyc><statusc>Y</statusc></ns2:SoftWare>'),
    ('<ns2:custom-data xmlns:ns2="http://www.example.com/2"><timec>2016.01.02</timec><customer>8R</customer><keyc>8R</keyc><statusc>N</statusc></ns2:custom-data>')

SELECT
    Nodes.KeyC.value('.', 'VARCHAR(50)') AS KeyC
FROM @Data D
    CROSS APPLY XmlText.nodes('//keyc') AS Nodes(KeyC)

This outputs the following:

KeyC
-----------
123-ABC
8R
like image 152
Jason W Avatar answered Feb 28 '26 22:02

Jason W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!