简体   繁体   English

从SQL Server中的XML字段中选择一个值

[英]Select a value from an XML field in SQL Server

I have an XML column in a SQL Server table. 我在SQL Server表中有一个XML列。 The XML is something like this: XML是这样的:

    <Dictionary>
        <Keys>
            <GenericKeys>
                <GenericKey>
                    <KeySets>
                        <KeySet>
                            <Key>A</Key>
                            <Value>123</Value>
                        </KeySet>
                        <KeySet>
                            <Key>B</Key>
                            <Value>456</Value>
                        </KeySet>
                        <KeySet>
                            <Key>C</Key>
                            <Value>789</Value>
                        </KeySet>
                    </KeySets>
                </GenericKey>
            </GenericKeys>
        </Keys>
    </Dictionary>

How can I query the value of Key B? 如何查询密钥B的值? In this example I need the value 456. 在此示例中,我需要值456。

Here is one way using value method 这是value法的一种方法

SELECT Key = r.value('(./Key)[1]', 'varchar(100)'),
       Value = r.value('(./Value)[1]', 'int')
FROM   Yourtable a
       CROSS APPLY xmlcolumn.nodes('/Dictionary/Keys/GenericKeys/GenericKey/KeySets/KeySet') AS x(r) 
WHERE  r.value('(./Key)[1]', 'varchar(100)') = 'B' 

If you need nothing more than the Value to a given Key you can try it like this: 如果您只需要给定键的值,则可以这样尝试:

DECLARE @xml XML=
N'<Dictionary>
        <Keys>
            <GenericKeys>
                <GenericKey>
                    <KeySets>
                        <KeySet>
                            <Key>A</Key>
                            <Value>123</Value>
                        </KeySet>
                        <KeySet>
                            <Key>B</Key>
                            <Value>456</Value>
                        </KeySet>
                        <KeySet>
                            <Key>C</Key>
                            <Value>789</Value>
                        </KeySet>
                    </KeySets>
                </GenericKey>
            </GenericKeys>
        </Keys>
    </Dictionary>';

--directly (hardcoded)
SELECT @xml.value(N'(//KeySet[Key="B"]/Value/text())[1]','int');

--Pass the key through a variable
DECLARE @SearchFor VARCHAR(100)='B';
SELECT @xml.value(N'(//KeySet[Key=sql:variable("@SearchFor")]/Value/text())[1]','int');

In general it is best to avoid the deep search with // . 通常,最好避免使用//进行深度搜索 The advise is: Be as specific as possible. 建议是:尽可能具体。 So the best (and fastest) was: 因此,最好的(也是最快的)是:

SELECT @xml.value(N'(/Dictionary/Keys/GenericKeys/GenericKey/KeySets/KeySet[Key=sql:variable("@SearchFor")]/Value/text())[1]','int');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM