T-SQL将二级XML节点分成多行

时间:2017-04-13 10:49:40

标签: sql-server xml

我觉得这应该是非常简单的事情,但我似乎无法弄明白。

给出以下XML:

<Responses>
  <Response>
    <ResponseId>1</ResponseId>
    <DateCreated>2016-02-01T18:26:17Z</DateCreated>
    <Detail>
      ...
    </Detail>
  </Response>
  <Response>
    <ResponseId>2</ResponseId>
    <DateCreated>2016-02-01T18:33:28Z</DateCreated>
    <Detail>
      ...
    </Detail>
  </Response>
  <Response>
    <ResponseId>3</ResponseId>
    <DateCreated>2016-02-12T19:33:48Z</DateCreated>
    <Detail>
      ...
    </Detail>
  </Response>
  <Response>
    <ResponseId>4</ResponseId>
    <DateCreated>2016-02-15T18:21:09Z</DateCreated>
    <Detail>
      ...
    </Detail>
  </Response>
  <Response>
    <ResponseId>5</ResponseId>
    <DateCreated>2016-02-15T19:04:07Z</DateCreated>
    <Detail>
      ...
    </Detail>
  </Response>
</Responses>

我期待如下结果: enter image description here

我能够很好地检索每个节点的元素(即,ResponseId,DateCreated和Detail导致五行,每行3列),但我需要返回完整的响应节点xml。

目前,我能想到的唯一解决方案是在检索ResponseId,DateCreated和Detail之后手动重新构建所需的结果,但这对我来说似乎是一个混乱且容易出错的选项。

1 个答案:

答案 0 :(得分:1)

您可以使用.nodes().query()

DECLARE @xml XML=
N'<Responses>
  <Response>
    <ResponseId>1</ResponseId>
    <DateCreated>2016-02-01T18:26:17Z</DateCreated>
    <Detail>
    </Detail>
  </Response>
  <Response>
    <ResponseId>2</ResponseId>
    <DateCreated>2016-02-01T18:33:28Z</DateCreated>
    <Detail>
    </Detail>
  </Response>
  <Response>
    <ResponseId>3</ResponseId>
    <DateCreated>2016-02-12T19:33:48Z</DateCreated>
    <Detail>
    </Detail>
  </Response>
  <Response>
    <ResponseId>4</ResponseId>
    <DateCreated>2016-02-15T18:21:09Z</DateCreated>
    <Detail>
    </Detail>
  </Response>
  <Response>
    <ResponseId>5</ResponseId>
    <DateCreated>2016-02-15T19:04:07Z</DateCreated>
    <Detail>
    </Detail>
  </Response>
</Responses>';

- 选择

SELECT One.Resp.query(N'.')
FROM @xml.nodes(N'/Responses/Response') AS One(Resp)