SQL选择:从XML字段中提取值。

3

我在使用SQL Select语句时,遇到了从XML字段中提取值的困难。

XML字段名称为Info,所在表格为results。

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

我需要获取属性DataValue。对于上面的记录,我需要的是2。

非常感谢您的帮助。


请在您的问题中标记相关的关系型数据库。答案是特定于平台的。 - Zohar Peled
微软SQL服务器 - Colin Edgar
1个回答

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。

@BogdanSahlean,我知道... OP没有提到关于重复的Result节点的任何信息... 父级的名称Results可能指向这个问题... 我会投票支持你的答案,因为它解决了一个合理的假设。现在就看OP如何决定了... - Shnugo
@Shnugo:我只是说OP没有提到这个话题。此外,他/她应该意识到这个假设。谢谢。 - Bogdan Sahlean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接