Domanda

I would like to add a node with a value from a table column. my example is below

declare @table table (bookid int,xmlCol xml)
insert into @table
select 1,
'<book title="you are not alone" author="Esther">
  <EDITIONS>
    <edition year="2012"/>
    <edition year="2013"/>
  </EDITIONS>
</book>'

declare @table1 table(bookid int,seller varchar(5))
insert into @table1
select 1,'xyz' 

select ??? 
from @table t
inner join @table1 t1
on t.bookid = t1.bookid

I want my final result to look like this

<book title="you are not alone" author="Esther">
  <EDITIONS>
    <edition year="2012"/>
    <edition year="2013"/>
  </EDITIONS>
 <seller> XYZ</seller>
</book>

I DONT WANT TO UPDATE, i think it can be done in xquery but I could not find any example of how to do this. I had a similar question a while ago on adding an attribute and was satisfied with the answer by Roman Pekar. add column value to an xml field as an attribute

È stato utile?

Soluzione

There is no way to add elements to existing XML in a query. You can however recreate the XML using the XML itself and adding the new elements or attributes you need.

Roman Pekar showed in his answer to your other question a technique you can use and if you understand what he does you should be able to adapt that answer to work for you here.

You need to create a new root element book, add the attributes from the existing element book, add the sub elements from book and finally add the new element using sql:column to pull in the value.

select T.xmlCol.query('element book {
                                    book/@*,                    (:Add attributes from root node:) 
                                    book/*,                     (:Add sub nodes from root node:)
                                    element seller              (:Add the new element:)
                                      {sql:column("T1.seller")} (:Get the value for the new node:)
                                    }')
from @table as T
  inner join @table1 as T1
    on T.bookid = T1.bookid
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top