SQL“用于XML路径" -嵌套结果 [英] SQL "For XML Path" - nested results
本文介绍了SQL“用于XML路径" -嵌套结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个表结构. YearPart,MonthPart和DatePart包含了它们所描述的内容……例如:2011、1、19(分别)
I have this table structure. YearPart, MonthPart and DatePart contain what they describe... EX: 2011, 1, 19 (respectively)
DECLARE @agenda AS TABLE (
PID INT IDENTITY(1,1) PRIMARY KEY,
YearPart int,
MonthPart int,
DayPart int,
lib_title nvarchar(200),
[filename] nvarchar(255),
meta_value nvarchar(2000)
)
使用此示例数据:
INSERT INTO @agenda VALUES (2010, 12, 4, 'Test Record', '', '')
INSERT INTO @agenda VALUES (2011, 1, 3, 'Another Record', '', '')
INSERT INTO @agenda VALUES (2011, 1, 3, 'Fred Birthday', '', '')
INSERT INTO @agenda VALUES (2011, 1, 4, 'Work Day', '', '')
INSERT INTO @agenda VALUES (2011, 12, 6, '2nd Test Record', '', '')
我想要的是这样的XML输出:
What I want, is an XML output like this:
<root>
<Year Year="2010">
<Month Month="12">
<Day Day="4">
<Item RecordName="Test Record" RecordID="1" />
</Day>
</Month>
</Year>
<Year Year="2011">
<Month Month="1">
<Day Day="3">
<Item RecordName="Another Record" RecordID="2" />
<Item RecordName="Geoffrey Birthday" RecordID="3" />
</Day>
<Day Day="4">
<Item RecordName="Work Day" RecordID="4" />
</Day>
</Month>
<Month Month="12">
<Day Day="6">
<Item RecordName="2nd Test Record" RecordID="5" />
</Day>
</Month>
</Year>
</root>
到目前为止,我还无法使嵌套正常工作.我通常以分组结束(例如,当只有一个Year = 2011元素时,我会得到多个).
So far, I haven't been able to get the nesting to work right. I usually end up with the grouping off (for example, I get multiple Year=2011 elements, when there should only be one).
如果无法做到这一点,我总是可以在.NET网站上创建XML ...
If this can't be done, I can always create the XML on the .NET site...
推荐答案
可以做到.
select
a1.YearPart as '@Year',
( select MonthPart as '@Month',
(select DayPart as '@Day',
(select
lib_title as '@RecordName',
PID as '@RecordID'
from @agenda as a4
where a4.DayPart = a3.DayPart and
a4.MonthPart = a2.MonthPart and
a4.YearPart = a1.YearPart
for xml path('Item'), type
)
from @agenda as a3
where a3.YearPart = a1.YearPart and
a3.MonthPart = a2.MonthPart
group by a3.DayPart
for xml path('Day'), type
)
from @agenda as a2
where a1.YearPart = a2.YearPart
group by a2.MonthPart
for xml path('Month'), type
)
from @agenda as a1
group by YearPart
for xml path('Year'), root
这篇关于SQL“用于XML路径" -嵌套结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文