XQuery 检索值

2021-10-02 00:00:00 xml sql xquery sql-server

我有以下 T-SQL 使用两个条件确定行是否存在:

I have the following T-SQL that determines if a row exists using two criteria:

Declare @x xml = '
    <row ParentID="45" ObjectID="0" Node="root.local.navigation[7]" itemKey="page" itemValue="Confirmation" itemType="string" />
    <row ParentID="45" ObjectID="0" Node="root.local.navigation[7]" itemKey="visited" itemValue="false" itemType="bool" />'

SELECT @x.exist('/row[@Node eq "root.local.navigation[7]"] and /row[@itemValue eq "Confirmation"]')

问题:鉴于上面的 SELECT,我如何选择第二行的 itemValue?即,由于有一行 Node="root.local.navigation[7]" 和 itemValue="Confirmation",在 node 相同且 itemKey="visited" 的行中返回 itemType 值?

Question: Given the above SELECT, how can I SELECT the second row's itemValue? i.e. Since there's a row with Node="root.local.navigation[7]" and itemValue="Confirmation", return the itemType value in the row where node is the same and itemKey="visited"?

推荐答案

这个怎么样:

declare @x xml = '
<row ParentID="45" ObjectID="0" Node="root.local.navigation[7]" itemKey="page" itemValue="Confirmation" itemType="string" />
<row ParentID="45" ObjectID="0" Node="root.local.navigation[7]" itemKey="visited" itemValue="false" itemType="bool" />'

select case when @x.exist('/row[@Node eq "root.local.navigation[7]"] and /row[@itemValue eq "Confirmation"]') = 1 
    then @x.value('/row[@Node eq "root.local.navigation[7]" and @itemKey eq "visited"][1]/@itemType', 'varchar(50)') 
end as item_type

相关文章