Reputation: 15630
Below is my xml
DECLARE @myDoc xml
DECLARE @ProdID int
SET @myDoc =
'<Root>
<ProductDescription>
<ProductID>1</ProductID>
<ProductName>Road Bike</ProductName>
<GenID>0C866AE2-7AAA-474F-8794-7538986268AE</GenID>
<VocID>AF05E961-9BC3-4249-A4A7-C6146D6FC614</VocID>
<Features>
<Warranty>1 year parts and labor</Warranty>
<Maintenance>3 year parts and labor extended maintenance is available</Maintenance>
</Features>
</ProductDescription>
<ProductDescription>
<ProductID>2</ProductID>
<ProductName>Road Bike2</ProductName>
<GenID>D1DCAD29-08C6-401E-9A0A-2130DC5D8CD4</GenID>
<VocID>AF05E961-9BC3-4249-A4A7-C6146D6FC614</VocID>
<Features>
<Warranty>2 year parts and labor</Warranty>
<Maintenance>4 year parts and labor extended maintenance is available</Maintenance>
</Features>
</ProductDescription>
</Root>'
SET @ProdID = @myDoc.value('(/Root/ProductDescription/ProductID)[2]', 'int' )
SELECT @ProdID
This will give me the ID for second item. If I change
I have the GenID
and VocID
. Using that I need to query and get the other data.
Kindly help me to generate query for the same.I am using SQL Server 2012. Thanks in advance.
Upvotes: 0
Views: 1202
Reputation: 69769
I would select directly from the XML data and just move the item number you are selecting to the nodes
rather than selecting an ID then filtering by that ID. That way you already have access to the other information.
E.g.
SELECT ProductID = x.value('ProductID[1]', 'int'),
ProductName = x.value('ProductName[1]', 'varchar(100)'),
GenID = x.value('GenID[1]', 'uniqueidentifier')
FROM @myDoc.nodes('/Root/ProductDescription[2]') prod (x);
EDIT
To get the records that match a given GenID and VocID you can use the exist()
method:
DECLARE @VocID UNIQUEIDENTIFIER = 'AF05E961-9BC3-4249-A4A7-C6146D6FC614',
@GenID UNIQUEIDENTIFIER = 'D1DCAD29-08C6-401E-9A0A-2130DC5D8CD4';
SELECT ProductID = x.value('ProductID[1]', 'int'),
ProductName = x.value('ProductName[1]', 'varchar(100)'),
GenID = x.value('GenID[1]', 'uniqueidentifier')
FROM @myDoc.nodes('/Root/ProductDescription') prod (x)
WHERE x.exist('VocID[text() = sql:variable("@VocID")]') = 1
AND x.exist('GenID[text() = sql:variable("@GenID")]') = 1;
Upvotes: 2