How to insert FOR AUTO XML result into table?
I have retrieved the values from a table using
select * from tableABC
开发者_开发百科for xml auto, elements
Now, there is this exact table tableABC on another server into which I need to insert these retrieved values .
How to achieve that?
Test table and data
create table tableABC(A int, B bit, C varchar(10))
insert into tableABC values(1, 1, 'Row 1')
insert into tableABC values(2, 0, 'Row 1')
Get the xml
declare @xml xml
set @xml = (select *
from tableABC
for xml auto, elements)
XML data
<tableABC>
<A>1</A>
<B>1</B>
<C>Row 1</C>
</tableABC>
<tableABC>
<A>2</A>
<B>0</B>
<C>Row 1</C>
</tableABC>
Insert into another tableABC
insert into tableABC(A, B, C)
select
r.value('A[1]', 'int'),
r.value('B[1]', 'bit'),
r.value('C[1]', 'varchar(10)')
from @xml.nodes('tableABC') t(r)
Edit Copy this entire statement to test if it works
use tempdb
go
create table tableABC(A int, B bit, C varchar(10))
go
insert into tableABC values(1, 1, 'Row 1')
insert into tableABC values(2, 0, 'Row 1')
declare @xml xml
set @xml = (select *
from tableABC
for xml auto, elements)
insert into tableABC(A, B, C)
select
r.value('A[1]', 'int'),
r.value('B[1]', 'bit'),
r.value('C[1]', 'varchar(10)')
from @xml.nodes('tableABC') t(r)
select *
from tableABC
go
drop table tableABC
Result is duplicated rows in tableABC
A B C
----------- ----- ----------
1 1 Row 1
2 0 Row 1
1 1 Row 1
2 0 Row 1
精彩评论