Home > Mobile >  XQuery - Fetch XML Value from SQL Server using XPath based on Condition
XQuery - Fetch XML Value from SQL Server using XPath based on Condition

Time:11-19

I have the following XML and you can see it contains three LevelA elements. I want to fetch /LevelA/Value (which is 9101) where /LevelA/LevelB2/LevelC == "Address". Now in PROD, the position of elements might change and so the address element might be first or last or in the middle. I am able to write two separate queries based on indexes but how to write one xpath query that contains the condition within it for matching with address and gives back 9101 independent of position of Level A elements.

DECLARE @x XML;
SET @x = '
<root>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Item4</LevelC>
            <LevelC2>Item5</LevelC2>
            <LevelC3>
                <anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">123456</anyType>
            </LevelC3>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:boolean">true</Value>
    </LevelA>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Item4</LevelC>
            <LevelC2>Item5</LevelC2>
            <LevelC3>
                <anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">123456</anyType>
            </LevelC3>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:boolean">true</Value>
    </LevelA>
    <LevelA>
        <LevelB>EqualTo</LevelB>
        <LevelB2>
            <LevelC>Address</LevelC>
            <LevelC2>House</LevelC2>
            <LevelC3/>
        </LevelB2>
        <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">9101</Value>
    </LevelA>
</root>
'
SELECT @x.value('/root[1]/LevelA[3][1]/LevelB2[1]/LevelC[1]', 'varchar(max)')
SELECT @x.value('/root[1]/LevelA[3][1]/Value[1]', 'int')

enter image description here

CodePudding user response:

You can do

SELECT @x.value('(/root/LevelA[LevelB2/LevelC = "Address"]/Value)[1]', 'int')

To apply the predicate to LevelA that LevelB2/LevelC/text() is "Address"

DB Fiddle

  • Related