Home >Database >Mysql Tutorial >How can I convert XML data to a SQL Server table using XQuery?
Converting XML Data to a Table in SQL Server
In SQL Server, you can convert XML data into a tabular format using the XML data type and XQuery expressions. Here's how:
Approach 1: Using Node Value Extractor
Suppose you have an XML document with data formatted like the following:
<row> <IdInvernadero>8</IdInvernadero> <IdProducto>3</IdProducto> <IdCaracteristica1>8</IdCaracteristica1> <IdCaracteristica2>8</IdCaracteristica2> <Cantidad>25</Cantidad> <Folio>4568457</Folio> </row> <row> <IdInvernadero>3</IdInvernadero> <IdProducto>3</IdProducto> <IdCaracteristica1>1</IdCaracteristica1> <IdCaracteristica2>2</IdCaracteristica2> <Cantidad>72</Cantidad> <Folio>4568457</Folio> </row>
To convert this XML into a table, you can use the following XQuery expression:
SELECT Tbl.Col.value('IdInvernadero[1]', 'smallint'), Tbl.Col.value('IdProducto[1]', 'smallint'), Tbl.Col.value('IdCaracteristica1[1]', 'smallint'), Tbl.Col.value('IdCaracteristica2[1]', 'smallint'), Tbl.Col.value('Cantidad[1]', 'int'), Tbl.Col.value('Folio[1]', 'varchar(7)') FROM @xml.nodes('//row') Tbl(Col)
Approach 2: Using Attribute Value Extractor
Alternatively, if your XML data is formatted with attributes instead of nodes, such as:
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" /> <row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
You can use the following XQuery expression:
SELECT Tbl.Col.value('@IdInvernadero', 'smallint'), Tbl.Col.value('@IdProducto', 'smallint'), Tbl.Col.value('@IdCaracteristica1', 'smallint'), Tbl.Col.value('@IdCaracteristica2', 'smallint'), Tbl.Col.value('@Cantidad', 'int'), Tbl.Col.value('@Folio', 'varchar(7)') FROM @xml.nodes('//row') Tbl(Col)
This query will extract the values from the XML attributes and convert them into a tabular format.
References:
The above is the detailed content of How can I convert XML data to a SQL Server table using XQuery?. For more information, please follow other related articles on the PHP Chinese website!