2009-11-18 103 views
0

我試圖從SQL查詢中獲取XML中的所有屬性和節點值。SQL Server 05:在查詢中從XML數據類型讀取值

我試着做下面的事情,但我錯過了輸出中的幾個值。 這裏是我的嘗試:

DECLARE @Details xml 
SET @Details = '<root> 
    <SelectedCategory CategoryId="101"> 
     <ItemID>120</ItemID> 
     <ItemID>256</ItemID> 
    </SelectedCategory> 
    <SelectedCategory CategoryId="125"> 
     <ItemID>158</ItemID> 
     <ItemID>120</ItemID> 
    </SelectedCategory> 
    <SelectedCategory CategoryId="15"> 
     <ItemID>5986</ItemID> 
     <ItemID>20</ItemID> 
     <ItemID>268</ItemID> 
    </SelectedCategory> 
</root>' 
SELECT 
    SelCat.CatDet.value('(@CategoryId)[1]', 'int') as "CategoryID", 
    SelCat.CatDet.value('.', 'int') as "ItemID" 
FROM @Details.nodes('/root/SelectedCategory') as SelCat(CatDet) 

這是顯示輸出:

CategoryID  ItemID 
101   120256 
125   158120 
15   598620268 

雖然所需的輸出可以在以下任一:

CategoryID  ItemID 
    101  120 
    101  256 
    125  158 
    125  120 
    15  5986 
    15   20 
    15   268 

OR

CategoryID  ItemID 
    101  120 
    NULL  256 
    125  158 
    NULL  120 
    15  5986 
    NULL  20 
    NULL  268 

任何人都知道如何做到這一點?

回答

1

嘗試是這樣的

DECLARE @Details xml 
    SET @Details = '<root> 
     <SelectedCategory CategoryId="101"> 
      <ItemID>120</ItemID> 
      <ItemID>256</ItemID> 
     </SelectedCategory> 
     <SelectedCategory CategoryId="125"> 
      <ItemID>158</ItemID> 
      <ItemID>120</ItemID> 
     </SelectedCategory> 
     <SelectedCategory CategoryId="15"> 
      <ItemID>5986</ItemID> 
      <ItemID>20</ItemID> 
      <ItemID>268</ItemID> 
     </SelectedCategory> 
    </root>' 

    SELECT T.[CategoryID], 
      T2.Loc.query('.').value('.', 'INT') Val 
    FROM 
     ( 
      SELECT 
       SelCat.CatDet.value('(@CategoryId)[1]', 'int') as CategoryID, 
       SelCat.CatDet.query('.') as ItemID 
      FROM @Details.nodes('/root/SelectedCategory') as SelCat(CatDet) 
     ) T 
     CROSS APPLY ItemID.nodes('/SelectedCategory/ItemID') as T2(Loc) 
+0

謝謝!它的作品:)但我是一個新手解析XML :(你能解釋這實際上是如何工作的? – Kay 2009-11-18 14:29:32

相關問題