SQL Server:使用 FOR XML PATH 嵌套元素

2022-01-07 00:00:00 xml nested sql sql-server for-xml-path

我想嵌套我的每个 XML 元素.

I want to nest each of my XML elements.

以下面的例子为例:

DECLARE @TempTable TABLE
(
    [Column1] char(10),
    [Column2] char(10)
);

INSERT INTO @TempTable([Column1], [Column2]) VALUES
('some value', 'some value'),
('some value', 'some value'),
('some value', 'some value'),
('some value', 'some value')

SELECT (
    SELECT * FROM @TempTable
FOR XML PATH('Row'), TYPE)
FOR XML PATH('ParentRow'), ROOT('Root')

这将返回以下 XML:

Which will return the following XML:

  <Root>
    <ParentRow>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
    </ParentRow>
  </Root>

这不是我想要格式化 XML 的方式.相反,我希望每个 元素都用一个 元素包裹,如下所示:

Which is not the way I want the XML to be formatted. Rather I want each <Row> element to be wrapped with a <ParentRow> element like below:

  <Root>
    <ParentRow>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
    </ParentRow>
    <ParentRow>
    <Row>
      <Column1>some value</Column1>
      <Column2>some value</Column2>
    </Row>
    </ParentRow>
    <ParentRow>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
    </ParentRow>
    <ParentRow>
      <Row>
        <Column1>some value</Column1>
        <Column2>some value</Column2>
      </Row>
    </ParentRow>
  </Root>    

对这些人有什么帮助吗?

Any help with this guys?

推荐答案

好的,这是代码.

DECLARE @TempTable TABLE
(
    [Column1] char(10),
    [Column2] char(10)
);

INSERT INTO @TempTable([Column1], [Column2]) VALUES
('some value', 'some value'),
('some value', 'some value'),
('some value', 'some value'),
('some value', 'some value')

SELECT (
        SELECT (
                SELECT T1.*
                FOR XML path('')
                    ,root('Row')
                    ,type
                )
        FROM @TempTable AS T1
        FOR XML path('ParentRow')
            ,type
        )
FOR XML path('Root')

这是输出.

<Root>
  <ParentRow>
    <Row>
      <Column1>some value</Column1>
      <Column2>some value</Column2>
    </Row>
  </ParentRow>
  <ParentRow>
    <Row>
      <Column1>some value</Column1>
      <Column2>some value</Column2>
    </Row>
  </ParentRow>
  <ParentRow>
    <Row>
      <Column1>some value</Column1>
      <Column2>some value</Column2>
    </Row>
  </ParentRow>
  <ParentRow>
    <Row>
      <Column1>some value</Column1>
      <Column2>some value</Column2>
    </Row>
  </ParentRow>
</Root>

祝你好运...

相关文章