2013-04-12 78 views
0

我需要一個select語句來解析xml並根據條件返回Ids。我如何在這種情況下使用循環?選擇查詢以基於值返回ID

我在xml中傳入了fruitIds。如果它們存在,則每個果實都在果實中檢查 - 如果它是新鮮的 - 0或不是-1。如果售罄 - (2)則不應考慮。該SP必須返回水果的不同的IDS有IsFresh設置爲0或1

CREATE PROCEDURE [dbo].[Fruits]  
@Data XML 
AS 

BEGIN TRY 

SET @Data = '<Fruits> 
<Fruit FruitID="1"></Fruit> 
    <Fruit FruitID="2"></Fruit> 
</Fruits>' 

SELECT DISTINCT(FruitType)  
from dbo.FruitsTable 
where FruitID = (SELECT Fruit.cols.value('@FruitID', 'INT') FruitID 
      FROM @Data.nodes('/Fruits/Fruit') Fruit(cols)) 
AND (Fruit.IsFresh = 0 OR Fruit.IsFresh = 1)      
END TRY 
BEGIN CATCH 
END CATCH 
GO 
FruitsTable 

     Composite Key = fruitid,buyerid 
     FruitID IsFresh BuyerID(this if FK) 
     1   0  1 
     2   1  2 
     3   0  2 
     4   0  3 
     5   2  1 
     1   1  2 

回答

1

塞特希,你都非常接近,這意味着你的邏輯是合理的,只是你的語法是關閉的。您需要使用IN而不是「=」(IN檢查數值是否在集合中)並修復表格別名:

SELECT DISTINCT f.FruitId 
from dbo.FruitsTable f 
where f.FruitID in (
      SELECT Fruit.cols.value('@FruitID', 'INT') FruitID 
      FROM @Data.nodes('/Fruits/Fruit') Fruit(cols)) 
     AND (f.IsFresh in (0,1))