如何使用内联ID在T-SQL中查询XML

时间:2019-02-09 14:30:53

标签: sql-server xml tsql

我将此XML存储在记录中,如何获取特定ID的值?

<Attributes>
<CustomerAttribute ID="4">
    <CustomerAttributeValue>
        <Value>1</Value>
    </CustomerAttributeValue>
</CustomerAttribute>
<CustomerAttribute **ID="5"**>
    <CustomerAttributeValue>
        <Value>**aaaaa**</Value>
    </CustomerAttributeValue>
</CustomerAttribute>

1 个答案:

答案 0 :(得分:0)

假设**周围的ID="5"和“ aaaaa”表示要选择的节点,下面是一种方法。

SELECT XmlColumn.value('(/Attributes/CustomerAttribute[@ID="5"]/CustomerAttributeValue/Value)[1]', 'varchar(100)')
FROM  dbo.xml
WHERE XmlColumn.exist('/Attributes/CustomerAttribute[@ID="5"]') = 1;

假设实际的XML值如下:

<Attributes>
    <CustomerAttribute ID="4">
        <CustomerAttributeValue>
            <Value>1</Value>
        </CustomerAttributeValue>
    </CustomerAttribute>
    <CustomerAttribute ID="5">
        <CustomerAttributeValue>
            <Value>aaaaa</Value>
        </CustomerAttributeValue>
    </CustomerAttribute>
</Attributes>