[英]Shape a FOR XML query against an xml column to include attribute in root
給定一個帶有xml列的表:
/*
CREATE TABLE #test (id int, content xml);
INSERT INTO #test VALUES (1, N'<i>abc</i>'),(1, N'<i>def</i>');
*/
我可以輕松地為下游反序列化創建一個xml文檔:
SELECT content AS [*]
FROM #test T
FOR XML PATH(''), ROOT('root')
收益:
/*
<root>
<i>abc</i>
<i>def</i>
</root>
*/
但是,我想向'root'添加一個屬性,理想的輸出為:
/*
<root tag="42">
<i>abc</i>
<i>def</i>
</root>
*/
到目前為止,我所能完成的就是在xml結構中添加一個附加級別:
SELECT 42 AS [@tag],
(SELECT content AS [*] FROM #test T FOR XML PATH(''), TYPE) AS [*]
FOR XML PATH('extra'), ROOT('root')
收益:
/*
<root>
<extra tag="42">
<i>abc</i>
<i>def</i>
</extra>
</root>
*/
因為
SELECT 42 AS [@tag],
(SELECT content AS [*] FROM #test T FOR XML PATH(''), TYPE) AS [*]
FOR XML PATH(''), ROOT('root')
是不允許的語法。 有沒有建議在不添加額外級別的情況下向根節點添加屬性?
好吧,答案現在似乎非常簡單,但是花了好幾次迭代才能得出:
SELECT 42 AS [@tag],
(SELECT content AS [*] FROM #test T FOR XML PATH(''), TYPE) AS [*]
FOR XML PATH('root')
我沒有意識到的FOR XML語法可以離開了兩個 ROOT和類型說明符,特別是因為這樣做會只產生一組片段的原始查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.