[英]SQL Server : creating XML with child nodes for non unique values
我很難弄清楚如何從具有子節點來存儲非唯一值的SQL select
中創建XML文件。
我正在使用Microsoft SQL Server 2012
例如
select company, founder
from companies
查詢的結果是:
microsoft corp Bill Gates
microsoft corp Paul Allen
apple inc Steve Jobs
apple inc Ronald Wayne
apple inc Steve Wozniak
我想生成一個XML
<values>
<company>microsoft corp</company>
<founders>
<founder id="1">Bill Gates</founder>
<founder id="2">Paul Allen</founder>
</founders>
</values>
<values>
<company>apple inc</company>
<founders>
<founder id="1">Steve Jobs</founder>
<founder id="2">Ronald Wayne</founder>
<founder id="3">Steve Wozniak</founder>
</founders>
</company>
</values>
我不確定是否需要節點<founders>
,我認為將創始人直接放在<values>
節點下對我來說也很好,因為他們會留在正確的公司中,並獲得ID以包含列表。
我現在使用FOR XML
,然后嘗試了以下不同的選項:
<values>
<company>apple inc</company>
<founder>Steve Jobs</founder>
</values>
<values>
<company>apple inc</company>
<founder>Ronald Wayne</founder>
</values>
<values>
<company>apple inc</company>
<founder>Steve Wozniak</founder>
</values>
這與我當時要實現的目標不兼容。
非常感謝所有將所有創建者置於同一<values>
節點下的幫助。
謝謝!
搜索了一下互聯網,找到了解決方案:
DECLARE @table TABLE (company VARCHAR(100), founder VARCHAR(100))
insert into @table SELECT 'microsoft corp', 'Bill Gates'
insert into @table SELECT 'microsoft corp', 'Paul Allen'
insert into @table SELECT 'apple inc', 'Steve Jobs'
insert into @table SELECT 'apple inc', 'Ronald Wayne'
insert into @table SELECT 'apple inc', 'Steve Wozniak'
SELECT company,
(
SELECT ROW_NUMBER()OVER( ORDER BY founder ) as 'founder/@id',
founder as 'founder'
FROM @table as F
WHERE F.company = Comp.company
FOR XML PATH(''), TYPE
) AS founders
FROM @table as Comp
GROUP BY company
FOR XML PATH('VALUES')
結果:
<VALUES>
<company>apple inc</company>
<founders>
<founder id="1">Ronald Wayne</founder>
<founder id="2">Steve Jobs</founder>
<founder id="3">Steve Wozniak</founder>
</founders>
</VALUES>
<VALUES>
<company>microsoft corp</company>
<founders>
<founder id="1">Bill Gates</founder>
<founder id="2">Paul Allen</founder>
</founders>
</VALUES>
測試數據
DECLARE @Companies TABLE (company VARCHAR(100), founder VARCHAR(100))
INSERT INTO @Companies VALUES
('microsoft corp', 'Bill Gates'),
('microsoft corp', 'Paul Allen'),
('apple inc', 'Steve Jobs'),
('apple inc', 'Ronald Wayne'),
('apple inc', 'Steve Wozniak')
詢問
SELECT company
,(SELECT ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Founder ASC) AS [@ID]
,B.founder [text()]
FROM @companies B
WHERE B.company = A.company
FOR XML PATH('Founder'),TYPE) AS Founders
FROM @companies A
GROUP BY A.Company
FOR XML PATH('values'),ROOT('Doc'), ELEMENTS
輸出值
<Doc>
<values>
<company>apple inc</company>
<Founders>
<Founder ID="1">Ronald Wayne</Founder>
<Founder ID="2">Steve Jobs</Founder>
<Founder ID="3">Steve Wozniak</Founder>
</Founders>
</values>
<values>
<company>microsoft corp</company>
<Founders>
<Founder ID="1">Bill Gates</Founder>
<Founder ID="2">Paul Allen</Founder>
</Founders>
</values>
</Doc>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.