[英]How Can I generate specific table from XML in sql server?
I have a xml document.我有一个 xml 文档。 I want to generate table with this xml.我想用这个 xml 生成表。 Here is my xml data这是我的 xml 数据
Declare @Result XML
SET @Result='
<General>
<Customer>
<model_year>2011</model_year>
<vehicle_id>1</vehicle_id>
<customer_requests>
<request>
<definition>I want to new car tyre</definition>
</request>
<request>
<definition>I want to new headlight</definition>
</request>
</customer_requests>
<mileage>34000</mileage>
</Customer>
<Customer>
<model_year>2012</model_year>
<vehicle_id>2</vehicle_id>
<customer_requests>
<request>
<definition>I want to general maintenance</definition>
</request>
</customer_requests>
<mileage>35000</mileage>
</Customer>
</General>
'
This is sample output这是样品 output
model_year型号年份 | vehicle_id车辆编号 | request要求 | mileage里程 |
---|---|---|---|
2011 2011 | 1 1 | I want to new car tyre,I want to new headlight我要换新轮胎,我要换大灯 | 34000 34000 |
2012 2012 | 2 2 | I want to general maintenance我要一般保养 | 35000 35000 |
How can I generate table from XML data like sample output with tsql?如何从 XML 数据(如示例 output 和 tsql)生成表?
Please try the following solution.请尝试以下解决方案。
It is using XQuery's FLWOR expression to concatenate multiple <definition>
tag values into one string.它使用 XQuery 的 FLWOR 表达式将多个<definition>
标记值连接到一个字符串中。
SQL SQL
DECLARE @Result XML =
N'<General>
<Customer>
<model_year>2011</model_year>
<vehicle_id>1</vehicle_id>
<customer_requests>
<request>
<definition>I want to new car tyre</definition>
</request>
<request>
<definition>I want to new headlight</definition>
</request>
</customer_requests>
<mileage>34000</mileage>
</Customer>
<Customer>
<model_year>2012</model_year>
<vehicle_id>2</vehicle_id>
<customer_requests>
<request>
<definition>I want to general maintenance</definition>
</request>
</customer_requests>
<mileage>35000</mileage>
</Customer>
</General>';
SELECT c.value('(model_year/text())[1]', 'CHAR(4)') AS model_year
, c.value('(vehicle_id/text())[1]', 'INT') AS vehicle_id
, c.query('for $x in customer_requests/request/definition
return if ($x is (customer_requests/request[last()]/definition)[1]) then data($x)
else concat($x/text()[1], ",")')
.value('text()[1]', 'VARCHAR(MAX)') AS request
, c.value('(mileage/text())[1]', 'INT') AS mileage
FROM @Result.nodes('/General/Customer') AS t(c);
Output Output
+------------+------------+-------------------------------------------------+---------+
| model_year | vehicle_id | request | mileage |
+------------+------------+-------------------------------------------------+---------+
| 2011 | 1 | I want to new car tyre, I want to new headlight | 34000 |
| 2012 | 2 | I want to general maintenance | 35000 |
+------------+------------+-------------------------------------------------+---------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.