繁体   English   中英

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

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

我在SQL Server表中有一个XML列。 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>

如何查询密钥B的值? 在此示例中,我需要值456。

这是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' 

如果您只需要给定键的值,则可以这样尝试:

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');

通常,最好避免使用//进行深度搜索 建议是:尽可能具体。 因此,最好的(也是最快的)是:

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