Click here to Skip to main content
15,884,629 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table with an XML Column called Vehicle.

The XML looks like this:

XML
<vehicle>
 <sedan>
  <type color="red" make="honda" year="2019">
   <dealers>
    <dealer address="1234 Cat Drive">
    <dealer address="1944 Dog Drive">
   </dealers>
  </type>
 </sedan>
</vehicle>


For example, I want to select a row based on the address value:
How do I select all data from the XML where the address equals
1234 Cat Drive


What I have tried:

So far what I tried is using the query method.
But there has to be a better way, I also see a lot of web examples but nothing specific to how I can get a row by passing a value.

SQL
SELECT Vehicles.query('/vehicles/sedan/type/dealers/dealer[@address="1944 Dog Drive"]')
Posted
Updated 13-Aug-19 23:53pm

 
Share this answer
 
If you just want to select the rows from the table where that address exists within the XML column:
SQL
DECLARE @AddressToFind nvarchar(100) = N'1234 Cat Drive';

SELECT
    Vehicle,
    OtherColumns
FROM
    YourTable
WHERE
    Vehicle.exist('//dealer[@address = sql:variable("@AddressToFind")]') = 1
;
exist() Method (xml Data Type) - SQL Server | Microsoft Docs[^]
Binding Relational Data Inside XML Data - SQL Server | Microsoft Docs[^]

If you want to return parts of the XML document, you can either use query or nodes to shred the document.

query() Method (xml Data Type) - SQL Server | Microsoft Docs[^]
nodes() Method (xml Data Type) - SQL Server | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900