【问题标题】:How to loop xml in store procedure如何在存储过程中循环xml
【发布时间】:2020-04-25 04:37:24
【问题描述】:

我有一个返回以下 XML 的存储过程:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Header />
  <SOAP-ENV:Body>
    <ns2:ReportResponse>
      <ns2:responseTitle />
      <ns2:responseBody>
        <ns2:resultRow>
          <ns2:result Name="country" Value="United Kingdom" />
          <ns2:result Name="code" Value="7360" />
        </ns2:resultRow>
        <ns2:resultRow>
          <ns2:result Name="country" Value="France" />
          <ns2:result Name="code" Value="7340" />
        </ns2:resultRow>
      </ns2:responseBody>
    </ns2:ReportResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我希望能够保存表中的 2 条记录,如何循环获取数据?

记录 1: 国家=英国 代码=7360

记录 2: 国家=法国 代码=7340

我尝试使用此选择,但没有返回任何内容。

SELECT 
    Record.value('@Name','VARCHAR')
FROM @XmlResponse.nodes('/Envelope/Body/ReportResponse/responseBody/resultRow')AS TEMPTABLE(Record)

谢谢。

【问题讨论】:

标签: sql-server xml stored-procedures xml-parsing


【解决方案1】:

像这样:

declare @doc xml = '
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Header />
  <SOAP-ENV:Body>
    <ns2:ReportResponse xmlns:ns2="http://whatever">
      <ns2:responseTitle />
      <ns2:responseBody>
        <ns2:resultRow>
          <ns2:result Name="country" Value="United Kingdom" />
          <ns2:result Name="code" Value="7360" />
        </ns2:resultRow>
        <ns2:resultRow>
          <ns2:result Name="country" Value="France" />
          <ns2:result Name="code" Value="7340" />
        </ns2:resultRow>
      </ns2:responseBody>
    </ns2:ReportResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
';

WITH XMLNAMESPACES ('http://schemas.xmlsoap.org/soap/envelope/' as soap ,
                    'http://whatever' as ns2)
SELECT 
    Record.value('(ns2:result[@Name="country"])[1]/@Value','VARCHAR(20)') Country,
    Record.value('(ns2:result[@Name="code"])[1]/@Value','int') Code
FROM @doc.nodes('/soap:Envelope/soap:Body/ns2:ReportResponse/ns2:responseBody/ns2:resultRow')AS TEMPTABLE(Record)

输出

Country              Code
-------------------- -----------
United Kingdom       7360
France               7340

(2 rows affected)

【讨论】:

  • 太好了,现在可以使用了。谢谢 - 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2013-03-04
  • 2014-05-27
相关资源
最近更新 更多