开发者

Return all xml nodes import into SQL Server

开发者 https://www.devze.com 2022-12-16 07:43 出处:网络
I have imported an xml document into SQL Server, I am now trying to import various parts into different tables. When I use the below query it only returns one row of hotel_facilities, I need to return

I have imported an xml document into SQL Server, I am now trying to import various parts into different tables. When I use the below query it only returns one row of hotel_facilities, I need to return all the hotel_facilities with the hotel_ref.

DECLARE @Details xml 
    SET @Details = '<hotels>
 <hotel>
  <hotel_ref>105</hotel_ref> 
 <hotel_facilities>
  <id>2</id> 
  <name>Disabled Facilities</name> 
  <id>4</id> 
  <name>24 Hour Reception</name> 
  <id>12</id> 
  <name>Restaurant</name> 
  </hotel_facilities>
  </hotel>
</hotels>'  

SELECT tab.col.value('../hotel_ref[1]','varchar(100)') AS 'hotel_ref',
tab.col.value('./id[1]','varchar(100)') AS 'HotelFacilityID',
tab.col.value('./name[1]','varchar(100)') AS 'HotelFacilityName'
FROM @Details.nodes('//hotels/hotel/hotel_facilities') AS tab(col)
开发者_如何学编程


Your XML is structured a bit funny - the <hotel_facilities> doesn't contain a proper "sub-entity" which you could enumerate over......

If your facilities would be wrapped into a <facility>....</facility> element, you could easily enumerate that.

   <hotel_facilities>
      <facility>
         <id>2</id> 
         <name>Disabled Facilities</name> 
      </facility>
      <facility>
         <id>4</id> 
         <name>24 Hour Reception</name> 
      </facility>
      <facility>
         <id>12</id> 
         <name>Restaurant</name> 
      </facility>
   </hotel_facilities>

But with your current setup, I think you'll be hard-pressed to find a good solution....


I agree with marc_s The XML does not have a good schema.

The closest I could get is:

SELECT tab.col.value('./hotel_ref[1]','varchar(100)') AS 'hotel_ref', 
fac.value('(.)[1]','varchar(100)') AS 'HotelFacilityID', 
ROWID=IDENTITY(int,1,1) 
into #facilitiesid 
FROM @Details.nodes('/hotels/hotel') AS tab(col) 
cross apply col.nodes('.//id') a(fac) 


SELECT tab.col.value('../hotel_ref[1]','varchar(100)') AS 'hotel_ref', 
fac.value('(.)[1]','varchar(100)') AS 'HotelFacilityName', 
ROWID=IDENTITY(int,1,1) 
into #facilitiesnames 
FROM @Details.nodes('//hotels/hotel/hotel_facilities') AS tab(col) 
cross apply col.nodes('.//name') a(fac) 

select i.hotel_ref, HotelFacilityID, HotelFacilityName 
from #facilitiesid i 
inner join #facilitiesnames n 
    on i.rowid = n.rowid 
0

精彩评论

暂无评论...
验证码 换一张
取 消