I have table which is having XML column. Now this XML column have multiple tags like an array. Each of these tags have an attribute() which i want to update from a table by joining it.
Table_A is as following
Id XML
1 "<Root><Object ObjId = "1" Text = "A"><Object Id = "2" Text = "B"></Root>"
2 "<Root><Object ObjId = "1" Text = "M"><Object Id = "12" Text = "N"></Root>"
Each of this XML is as following
<Root>
<Object Id = "1" Text = "A">
<Object Id = "2" Text = "B">
<Object Id = "3" Text = "C">
<Object Id = "4" Text = "D">
<Object Id = "5" Text = "E">
</Root>
Table_B i want to join to update records in XML:
Table_A_Id ObjId Value
1 1 "Q"
1 2 "R"
2 1 "S"
2 12 "T"
I couldn't find the solution to create a dynamic path in XML.modify method. Following is the query i have started, which might explain what i am trying to do.
UPDATE TblA SET XML.modify(replace value of (/Root/Object) with Table_B.Value)
FROM TABLE_A TblA
CROSS APPLY TblA.XML.nodes('/Root/Object') AS xmlObjs(obj)
INNER JOIN Table_B TblB ON TblB.Table_A_Id = TblA.Id AND TblB.ObjId = xmlObjs.obj.value('@ObjId[1]','varchar(MAX)')
What you seem to know is:
.modify()will not allow more than one change per call. You would have to use aCURSORorWHILEloop in order to update each occurance one after the other.Therefore I'd suggest this approach:
First we create mockup tables to simulate your issue:
--The query
--Check the result
The idea in short:
UPDATE
Next time please try to avoid a chameleon question... Your comment let this change into something entirely different... Next time please close one question, if it is answered as is and start a new question in case you find, that your initial question did not really cover your needs...
Try this:
The idea behind:
We need to get the side data into the XML in order to use XQuery-FLWOR.
The
APPLYwill create a XML like this:Against this combined XML we can run a FLWOR query using
.query().<Root><Value>of your side data (in the XML its<b_data>) is assigned to$bVal.<Object>.IdandTextdirectly and add all other attributes without looking into them.The result for the Id=1 looks like this afterwards:
You can see, that "Q" and "R" are changed where Id is 1 or 2 - according to the side data.
I must admit, that this gets complicated...
Depending on your real data and the complexity of your XML a looping approach with
.modify()might be better...