0

I have a table named VehicleHistoryBlob that has the following structure:

VehicleHistoryBlobId int PRIMARY KEY
VehicleHistoryBlob XML

I need to write SQL that finds all entries in VehicleHistoryBlob XML that have Bus as a parent node and Destination as a child node (Bus can have many Destinations, and the parent node in the XML is not always a Bus).

<Bus>
...
    <Destination>
            <Name>The big building</Name>
            <DestinationCode> A21301423 </DestinationCode>
            <DestinationAddress> 440 Mountain View Parade </DestinationAddress>
            <DestinationCountry> USA </DestinationCountry>
    </Destination>
</Bus>'

I need to query through the XML and find all entries that have Bus as a parent node and Destination as a child node, and pass the VehicleHistoryBlobId associated with the XML into my temporary table @tmpTable

DECLARE @tmpTable TABLE(theints INT)

I have been trying to manipulate the .nodes function but I am struggling to yield accurate results due to my lack of experience with XML as a data type.

Thanks in advance!

1 Answer 1

2

To filter row by certain condition on the XML column, you can use exist() method instead of nodes(). For example, the following query insert to @temptable VehicleHistoryBlobId where corresponding XML has Bus as root element and Destination child element :

INSERT INTO @tmpTable
SELECT v.VehicleHistoryBlobId 
FROM VehicleHistoryBlob v
WHERE v.VehicleHistoryBlob.exist('/Bus/Destination') = 1

sqlfiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you so much @har07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.