SQL Select:从XML字段中获取值

时间:2016-06-06 08:48:05

标签: sql sql-server xml xpath xquery

我正在努力使用SQL Select Statement从XML字段中提取一个值。

XML字段是Info,表格是结果。

<Screens>
  <Results>
    <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
          DataAction="" DataValue="2" DataScore="0" />
  </Results>
</Screens>

我需要提取属性DataValue。对于上面的记录,我会寻找2。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

使用SQL Server就是这样:

DECLARE @xml XML=
'<Screens>
  <Results>
    <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
          DataAction="" DataValue="2" DataScore="0" />
  </Results>
</Screens>';

SELECT @xml.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue

编辑:数据来自表格

只需将我的@tbl替换为您的实际表格

即可
--test scenario with two data rows, one has DataValue=2 the other =99
DECLARE @tbl TABLE(ID INT IDENTITY,info XML);
INSERT INTO @tbl(info) VALUES
 (
    '<Screens>
      <Results>
        <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
              DataAction="" DataValue="2" DataScore="0" />
      </Results>
    </Screens>'
 )
,(
    '<Screens>
      <Results>
        <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
              DataAction="" DataValue="99" DataScore="0" />
      </Results>
    </Screens>'
 );

--this is the query
SELECT info.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue
FROM @tbl

结果是2和99

答案 1 :(得分:1)

我假设一个Results元素(s)可以有一个或多个Result子元素:

DECLARE @x XML
SET @x = N'<Screens>
  <Results>
    <Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse="" 
          DataAction="" DataValue="2" DataScore="0" />
    <Result ID="54722094-8b36-4a01-b089-aaaaaaaaaaaa" DataResponse="" 
          DataAction="" DataValue="3" DataScore="0" />
  </Results>
</Screens>'

SELECT  x.XmlCol.value('(@DataValue)[1]', 'INT') AS DataValueAsINT
FROM    @x.nodes(N'Screens/Results/Result') x(XmlCol)

结果:

DataValueAsINT
--------------
2
3