I have two table. One table hold key column and xml column. Other table hold data. When I try to form xml from second table and update first table. It is updating only one node, it ignores second node. Please refer this example.
declare @mytable table
(
col1 int,
col2 varchar(100)
)
declare @mytable1 table
(
col1 int,
col2 xml
)
insert into @mytable1 values(1,null)
insert into @mytable1 values(2,null)
insert into @mytable values(1,'abc')
insert into @mytable values(1,'dcf')
insert into @mytable values(2,'efg')
insert into @mytable values(2,'hhh')
update x set col2= d.XMLCol from @mytable1 x
inner join
(select a.col1, node.XMLCol from @mytable a join @mytable1 b on a.col1=b.col1 cross apply (select a.col1,a.col2 for xml path('record') , root ('myroot'), type
) as node(XMLCol) )d
on x.col1=x.col1
select * from @mytable1
The actual result is
1 <myroot><record><col1>1</col1><col2>abc</col2></record></myroot>
2 <myroot><record><col1>2</col1><col2>hhh</col2></record></myroot>
Expected result is
1 <myroot><record><col1>1</col1><col2>abc</col2></record><record><col1>1</col1><col2>dcf</col2></record></myroot>
2 <myroot><record><col1>2</col1><col2>hhh</col2></record><record><col1>2</col1><col2>efg</col2></record></myroot>
Can someone please point out what am I doing wrong?
Thanks,
Esen.
@mytable1on the same column producing a Cartesian product.on x.col1=x.col1.@mytable1. The first row with the first node and the second row with the second node. The update statement will not combine those rows to one, it will pick one of them.Do it like this instead:
SE-Data