0

我已将一个 xml 文档导入 SQL Server,我现在正尝试将各个部分导入不同的表中。当我使用下面的查询时,它只返回一行hotel_facilities,我需要返回所有hotel_facilities 和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)
4

2 回答 2

2

您的 XML 结构有点滑稽 -<hotel_facilities>它不包含您可以枚举的适当“子实体”......

如果您的设施将被包装到一个<facility>....</facility>元素中,您可以轻松地枚举它。

   <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>

但是以您当前的设置,我认为您将很难找到一个好的解决方案....

于 2010-01-12T17:32:17.270 回答
0

我同意 marc_s XML 没有一个好的架构。

我能得到的最接近的是:

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 
于 2010-01-12T17:43:54.490 回答