Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Parsing with SQL query

I am trying to parse the below xml in sql server to get all the 3 Ids

<Configuration>
  <ID>1000</ID>
  <ID>1001</ID>
  <ID>1002</ID>
</Configuration>

using the query

SELECT  CONFIGURATION.value('/', 'varchar(200)') as SID FROM SCHEDULE 

am getting the results as 100010011002 but i would like to have the results in a column or in a CSV format.

any help would be appriciated.

like image 756
Deevin Avatar asked Jan 12 '11 14:01

Deevin


People also ask

How do I query XML data in SQL?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.

What is XML parsing in SQL?

First, the sp_xml_preparedocument stored procedure parses the XML document. The parsed document is a tree representation of the nodes (elements, attributes, text, and comments) in the XML document. OPENXML then refers to this parsed XML document and provides a rowset view of all or parts of this XML document.

Can you use SQL in XML?

Many SQL statements support the XML data type. This enables you to perform many common database operations with XML data, such as creating tables with XML columns, adding XML columns to existing tables, creating triggers on tables with XML columns, and inserting, updating, or deleting XML documents.

Which technique can you use to read XML from SQL Server?

Read the XML file using OPENROWSET, and save the data in the table. In the below code, we create a table for our raw XML data. Then read the XML file and save the same data into the "PointsXML" table. CREATE TABLE PointsXML -- Create table for raw XML file.


1 Answers

Using MS SQL Server, this will give you rows.

declare @xml as xml
set @xml = 
'<Configuration>
  <ID>1000</ID>
  <ID>1001</ID>
  <ID>1002</ID>
</Configuration>'

select
    x.i.value('.', 'int') as ID
from @xml.nodes('/Configuration/ID') as x(i)

If you only need one value like in this example it is a lot faster (three times) to shred on the text() node.

select
    x.i.value('.', 'int') as ID
from @xml.nodes('/Configuration/ID/text()') as x(i)
like image 50
Mikael Eriksson Avatar answered Oct 16 '22 12:10

Mikael Eriksson