Sql 选择查询以根据值返回ID

Sql 选择查询以根据值返回ID,sql,sql-server,Sql,Sql Server,我需要一个select语句来解析xml并根据条件返回ID。在这种情况下如何使用循环 我已经在xml中传递了水果ID。如果果肉是新鲜的-0或不是-1,则在果肉稳定中检查每个果肉。如果售出-(2),则不应将其考虑在内。SP必须返回IsFresh设置为0或1的水果的不同ID CREATE PROCEDURE [dbo].[Fruits] @Data XML AS BEGIN TRY SET @Data = '<Fruits> <Fruit FruitID="1

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

我已经在xml中传递了水果ID。如果果肉是新鲜的-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

Senthil,你很接近,意思是你的逻辑是正确的,只是你的语法不正确。您需要使用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))
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))