如何将select语句返回到变量中

时间:2014-04-14 13:20:36

标签: sql sql-server-2008

我有这个存储过程,

Create procedure [dbo].[Craping_GetFruitCrapedOrNot]
(
    @FruitID int,
    @CrateID int,
    @FruitName varchar(100)
)
AS
  SELECT CASE WHEN EXISTS
  (
     SELECT     Craping.CRAPED
     FROM         Fruits 
          INNER JOIN Craping 
          ON Fruits.ID = Craping.FruitID
     WHERE     
         (Fruits.FruitTable = @FruitName) 
         AND (Craping.FruitID = @FruitID) 
         AND (Craping.CrateID = @CrateID)
  ) 
  THEN 'False'
  ELSE 'True'
  END AS FruitNotCraped
GO  

现在如果存在则不是返回false THEN 'False'我想返回select语句返回的内容,不知道怎么回事?

Then return SELECT     Craping.CRAPED
         FROM         Fruits 
              INNER JOIN Craping 
              ON Fruits.ID = Craping.FruitID
         WHERE     
             (Fruits.FruitTable = @FruitName) 
             AND (Craping.FruitID = @FruitID) 
             AND (Craping.CrateID = @CrateID)

1 个答案:

答案 0 :(得分:3)

 DECLARE @Craped NVARCHAR(50)

 SELECT     @Craped = CONVERT(NVARCHAR(50), Craping.CRAPED)
 FROM         Fruits 
      INNER JOIN Craping 
      ON Fruits.ID = Craping.FruitID
 WHERE     
     (Fruits.FruitTable = @FruitName) 
     AND (Craping.FruitID = @FruitID) 
     AND (Craping.CrateID = @CrateID)

 SELECT CASE
            WHEN @@ROWCOUNT = 0 THEN 'True'
            ELSE @Craped
        END AS [FruitNotCraped]

注意:

  • 我测试了@@ ROWCOUNT而不是@Craped IS NULL,以防Craping.CRAPED字段可能为NULL作为有效值。