gpt4 book ai didi

sql-server - 在 SQL 中用外部节点包装内部 XML 节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:58:55 25 4
gpt4 key购买 nike

采用以下TSQL

SELECT 
o.id as '@id',
(SELECT
op.id as '@orderid'
FROM
Orders o
INNER JOIN
OrderParts op ON o.id = op.orderId
FOR XML PATH ('orderpart'), TYPE)
FROM
Orders o
FOR XML PATH ('order'), ROOT('application')

从这些表中生成。

订单

Id   type
----------------
1 Pending
2 Active

订购零件

id   orderid
-------------
1 1
2 1
3 3
4 2

它生成这个 XML

<application>
<order id="1">
<orderpart orderid="1" />
<orderpart orderid="2" />
<orderpart orderid="3" />
<orderpart orderid="4" />
</order>
<order id="2">
<orderpart orderid="1" />
<orderpart orderid="2" />
<orderpart orderid="3" />
<orderpart orderid="4" />
</order>
</application>

如何使用 TSQL 在 orders 和 orderparts 周围添加外部复数标签,使其看起来如下所示?

<application>
<orders>
<order id="1">
<orderparts>
<orderpart orderid="1" />
<orderpart orderid="2" />
<orderpart orderid="3" />
<orderpart orderid="4" />
</orderparts>
</order>
<order id="2">
<orderparts>
<orderpart orderid="1" />
<orderpart orderid="2" />
<orderpart orderid="3" />
<orderpart orderid="4" />
</orderparts>
</order>
</orders>
</application>

谢谢!

最佳答案

SELECT 
(
SELECT o.id AS '@id',
(
SELECT op.id as '@orderid'
FROM OrderParts op
WHERE op.orderID = o.ID
FOR XML PATH ('orderpart'), TYPE
) AS 'OrderParts'
FROM Orders o
FOR XML PATH ('order'),TYPE
)
FOR XML PATH ('orders'),ROOT('application')

关于sql-server - 在 SQL 中用外部节点包装内部 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28243312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com