使用SQL Server 2005从xml检索字段

时间:2012-04-06 07:51:47

标签: xml sql-server-2005 xpath

我有以下sql代码:

declare @x xml
set @x = 

'<ResultBlock>
    <MatchSummary matches="1"><TotalMatchScore>900</TotalMatchScore>
        <Rules totalRuleCount="9">
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_SWTEL_DEMP_DEADD</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_PAS_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_CTEL_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_PAS_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_CTEL_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_MS_PER</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_REF_PER</RuleID>
                <Score>100</Score></Rule>
        </Rules>
        <MatchSchemes schemeCount="1">
            <Scheme>
                <SchemeID>7</SchemeID>
                <Score>900</Score>
            </Scheme>
        </MatchSchemes>
    </MatchSummary>
    <ErrorWarnings>
        <Errors errorCount="0" />
        <Warnings warningCount="0" />
    </ErrorWarnings>
</ResultBlock>'

select  x.value(N'RuleID', N'varchar(50)') as RuleID
from @x.nodes(N'//RuleID') t(x)

我需要检索所有RuleID。但是以下查询会生成错误: XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'。什么可能是错的?

1 个答案:

答案 0 :(得分:2)

您已经关闭了 - 您的XPath将所有<RuleID>节点的列表作为XML片段返回 - 现在您要提取实际的元素值,因此您需要使用此SQL XQuery来实现此目的:

select 
    x.value('.', 'varchar(50)') as RuleID
from 
    @x.nodes('//RuleID') t(x)

.说:只是给我元素的内容 - 这就是你要找的东西,对吧?