【问题标题】:return parent and child data using FOR XML in a stored proc在存储过程中使用 FOR XML 返回父子数据
【发布时间】:2010-02-26 16:43:29
【问题描述】:

如果我有一个父表和一个子表,其中可以有一个父表和多个子表,我该如何从存储过程中的存储过程返回以下 xml?

<Parents>
    <Parent>
       <ID>Integer</ID>
       <Children>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
        </Children>
    </Parent>
    <Parent>
       <ID>Integer</ID>
       <Children>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
        </Children>
    </Parent>
</Parents>

【问题讨论】:

  • 没有机会升级到 SQL Server 2005 或 2008 ??在以后的版本中,一切 XML 都简单多了...
  • 老实说,在 SQL Server 2000 中 - 我只需将行选择到 C# 中并在那里处理所有繁琐的 XML 操作。 SQL Server 2000 中的 XML 一点也不好玩,杂乱、复杂且容易出错。省去你的麻烦!

标签: sql-server sql-server-2000 for-xml


【解决方案1】:

您可以使用一些嵌套选择来做到这一点。

select 'a' as "ID",
 (
 select child as "ID"
 from ( select 'integer' as child
   union all
   select 'string' ) a
   for xml path('Child'), type, root('Childrens') 
   ) as "*"
for xml path('Parent'), type, root('Parents')

Opps,我没有看到它是针对 Sql-Server-2000 的。

【讨论】:

  • 这也是我的解决方案 - 但不适用于 SQL Server 2000,唉..... :-(
  • (SQL Server 2000)+(XML)=哎哟! ;-o
【解决方案2】:

这对于 SQL 2000 来说肯定要困难得多。下面是一个示例查询,可以帮助您开始这个过程。请理解,它与您要查找的格式不完全一致。查询的目的是帮助您开始...朝着正确的方向轻推。

这里的技巧是使用 FOR XML EXPLICIT,并仔细设计列别名来控制元素的定位。

Declare @Parent Table(Id Int, Data VarChar(20))
Insert Into @Parent Values(1, 'Fruit')
Insert Into @Parent Values(2, 'Vegetable')

Declare @Child Table(Id Int, ParentId Int, Name VarChar(20))
Insert Into @Child Values(1, 1, 'Apple')
Insert Into @Child Values(2, 1, 'Banana')
Insert Into @Child Values(3, 2, 'Carrot')
Insert Into @Child Values(4, 2, 'Pea')

Select 1 As Tag,
       NULL As Parent,
       Id As [Parent!1!Id!Element],
       Data As [Parent!1!Data!Element],
       NULL As [Child!2!Id!Element],
       NULL As [Child!2!Name!Element]
From   @Parent P

Union

Select  2 As Tag,
        1 As Parent,
        P.Id,
        NULL,
        C.Id,
        Name
From    @Child C
        Inner Join @Parent P
          On C.ParentId = P.Id
Order By [Parent!1!Id!Element]
For XML Explicit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    相关资源
    最近更新 更多