[英]SQL Server parse XML to table - multiple node with the same name and first node should be table columns
I have a source xml like below and I want to convert to SQL table.我有一个源 xml 如下所示,我想转换为 SQL 表。 First "tr" node should be columns for the table and remaining are rows.
第一个“tr”节点应该是表的列,其余的是行。
<table>
<tbody>
<tr>
<td>Description</td>
<td>Value</td>
<td>Reference</td>
<td>Category</td>
<td>Review</td>
</tr>
<tr>
<td>Process Param</td>
<td>|ABCD|</td>
<td>Step1</td>
<td>Process</td>
<td>False</td>
</tr>
<tr>
<td>Config Param</td>
<td>|EFGH|</td>
<td>Step2</td>
<td>Config</td>
<td>True</td>
</tr>
<tr>
<td>Process Param</td>
<td>|IJKL|</td>
<td>Step3</td>
<td>Process</td>
<td>False</td>
</tr>
</tbody>
</table>
You can extract data from your html/xml structure using the nodes
method provided for the xml data type (more info here ).您可以使用为 xml 数据类型提供的
nodes
方法从您的 html/xml 结构中提取数据( 此处有更多信息)。
Here is a simple query that should put you on the right track:这是一个简单的查询,应该让您走上正轨:
select
Tbl.Col.value('td[1]', 'varchar(50)')
,Tbl.Col.value('td[2]', 'varchar(50)')
,Tbl.Col.value('td[3]', 'varchar(50)')
,Tbl.Col.value('td[4]', 'varchar(50)')
,Tbl.Col.value('td[5]', 'varchar(50)')
from @x.nodes('//tr') Tbl(Col)
where @x is a xml variable containing your xml:其中@x 是一个 xml 变量,其中包含您的 xml:
declare @x xml = '<table>...
The problem is that the first row (that contains column headers) is returned inside the dataset:问题是第一行(包含列标题)在数据集中返回:
If you want to use values in the first row as column names you'll have to write dynamic xml.如果要将第一行中的值用作列名,则必须编写动态 xml。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.