选择查询以根据值返回ID

时间:2013-04-12 11:08:47

标签: sql sql-server

我需要一个select语句来解析xml并根据条件返回Ids。在这种情况下我如何使用循环?

我在xml中传递了fruitIds。如果果实稳定,如果它是新鲜的0或不是1,则检查每个果实。如果售罄 - (2)那么就不应该考虑它。 SP必须返回IsFresh设置为0或1

的水果的不同ID
 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 个答案:

答案 0 :(得分:1)

Senthil,你非常接近,这意味着你的逻辑是正确的,只是你的语法是关闭的。您需要使用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))
相关问题