sql server 2005 create temporary table using xml parameter -


i want create temporary table xml input parameter. xml:

 <offices>         <group id="22807">             <office>185901</office>             <office>185902</office>             <office>185944</office>         </group>     </offices> 

this sql:

declare @groupsofficeids xml set @groupsofficeids = '<offices><group id="22807"><office>185901</office><office>185902</office><office>185944</office></group></offices>'  create table #groupofficeid (pk int primary key identity(1,1), idxml xml) insert #groupofficeid values (@groupsofficeids) select pk,  group.ref.value('@id', 'int') groupid,  group.ref.value('(office/text())[1]', 'varchar(20)') officeid #groupofficeid go cross apply go.idxml.nodes('/offices/group') group(ref)   

this returns 1 row:

pk  groupid     officeid 1   22807       185901 

i return following:

pk  groupid     officeid     1   22807       185901     2   22807       185902     3   22807       185944 

is xml wrong or query? thanks!

update got little bit further... query this:

declare @groupsofficeids xml set @groupsofficeids = '<offices><group id="22807"><office>185901</office><office>185902</office><office>185944</office></group></offices>'  create table #groupofficeid (pk int primary key identity(1,1), idxml xml) insert #groupofficeid values (@groupsofficeids) select pk,  group.ref.value('@id', 'int') groupid,  office.ref.value('(office/text())[1]', 'varchar(20)') officeid #groupofficeid go cross apply go.idxml.nodes('/offices/group') group(ref)   cross apply go.idxml.nodes('/offices/group/office') office(ref) 

it produces this:

pk  groupid     officeid 1   22807       185901 1   22807       185902 1   22807       185944 

why doesn't primary key increment 1?

you got same value pk because temp table stores 1 xml data in 1 row 1 pk, means data come same xml source have same primary key :

create table #groupofficeid (pk int primary key identity(1,1), idxml xml)                                 --  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                 --  here associate 1 xml data 1 identity id 

you may want alter temporary table structure store 1 groupid-officeid combination 1 row instead :

create table #groupofficeid (pk int primary key identity(1,1), groupid int, officeid int) 

then query insert (avoid using keyword go , group alias!) :

insert #groupofficeid(groupid,officeid) select     g.value('@id','int') groupid,     o.value('.','int') officeid @groupsofficeids.nodes('/offices/group') grp(g)      cross apply g.nodes('office') office(o) 

then select * #groupofficeid produce correct expected result :

pk  groupid     officeid 1   22807       185901 2   22807       185902 3   22807       185944 

sql fiddle demo


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -