代码之家  ›  专栏  ›  技术社区  ›  CaffGeek

SQL Server FOR XML路径嵌套问题

  •  2
  • CaffGeek  · 技术社区  · 14 年前

    问题很简单 SELECT * FROM [TABLENAME] ,是的,必须是 * 因为这用于需要在任何表上工作的动态实用程序。

    无论如何,我希望生成的记录像这样嵌套两层

    <Root>
       <RecordParent>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
       </RecordParent>
       <RecordParent>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
       </RecordParent>
       <RecordParent>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
       </RecordParent>
    </Root>
    

    SELECT ( 
        SELECT * FROM tableName FOR XML PATH('Record'), TYPE
    ) FOR XML PATH('RecordParent'), ROOT('Root')
    

    结果就像

    <Root>
       <RecordParent>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
          <Record>
              <!--Fields selected with * end up here-->
          </Record>
       </RecordParent>
    </Root>
    

    有什么办法让我得到正确的结果吗 FOR XML

    编辑

    我可以用几行字

    DECLARE @xml xml
    SET @xml = (SELECT TOP 10 * FROM tableName FOR XML PATH('Record'), ROOT('Records'))
    SELECT  r.query('.')FROM @xml.nodes('//Record') R(r) FOR XML PATH('RecordParent'), ROOT('Root'), TYPE
    
    4 回复  |  直到 14 年前
        1
  •  1
  •   CaffGeek    14 年前

    我可以用几行字

    DECLARE @xml xml
    SET @xml = (SELECT TOP 10 * FROM tableName FOR XML PATH('Record'), ROOT('Records'))
    SELECT  r.query('.')FROM @xml.nodes('//Record') R(r) FOR XML PATH('RecordParent'), ROOT('Root'), TYPE
    
        2
  •  0
  •   Lucero    14 年前

    当然可以使用FOR XML EXPLICIT得到结果,但这是一个PITA。因为FOR PATH不允许在路径中使用分隔符,所以我猜您不太可能使用这个分隔符,但是也许您可以使用应用于XML的XQuery来制作一些东西。

    http://msdn.microsoft.com/en-us/library/ms189068.aspx

        3
  •  0
  •   DForck42    14 年前

    这里有一个黑客:

    declare @table table (Id int identity(1,1), Name varchar(50))
    
    
    insert into @table values ('asdf')
    insert into @table values ('fdsa')
    insert into @table values ('fhgdf')
    insert into @table values ('qewry')
    insert into @table values ('sdtkjfhj')
    
    
    
    select
    (
    select *
    from @table
    for XML PATH('Record'), ROOT('RecordParent'), type
    ) for xml path('root')
    
        4
  •  0
  •   Sameh    12 年前

    您可以定义它使用/用于层次结构

    id为“RecordParent/Record/ClientID” 来自客户 对于XML根('ROOT')