xml - SQL "For XML Path"- 嵌套结果

标签 xml tsql path nested

我有这个表结构。 YearPart、MonthPart 和 DatePart 包含它们描述的内容...例如:2011、1、19(分别)

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 输出:

<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 元素,而实际上应该只有一个)。

如果做不到,我总是可以在 .NET 站点上创建 XML...

最佳答案

这是可以做到的。

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

关于xml - SQL "For XML Path"- 嵌套结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4751131/

相关文章:

SQL IN 语句使用类似的语法?

sql - 仅当传递的参数具有值时才使用 Where 子句中的 'Exists'

windows - 修改for循环批处理文件中的变量

java - 从 GNOME 运行时如何获取可运行的 .jar 文件的位置

python - 我如何检查python中存在多少路径

Java + ResultSet.getObject()

php - Xpath访问XML标记内的属性值

android - 设计 View 中底部导航的实时 View 不显示图标和菜单资源

android - 我应该使用 LinearLayout 还是 RelativeLayout 让 4 个对象填满屏幕?

sql - 如何检查 SQL Server 中的重复记录