简体   繁体   English

存储过程,如果不存在任何记录

[英]Stored Procedures If no record exists

I got this stored procedure, 我得到了这个存储过程,

Create procedure [dbo].[Craping_GetFruitCrapedOrNot]
(
    @FruitID int,
    @CrateID int,
    @FruitName varchar(100)
)
AS
    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)
GO

Now I want to check if Fruits table has the fruit with provided fruit name, if there isn't any fruit then return true. 现在,我要检查“水果”表是否具有提供了水果名称的水果,如果没有任何水果,则返回true。

If Fruits and Craping table's inner join got no record for a FruitID , CrateID and FruitName then return true not false. 如果Fruits and Craping表的内部Craping没有获得FruitIDCrateIDFruitName记录,则返回true而不是false。

What we are trying to do is to only get false when a fruit is craped and logged to table. 我们正在尝试做的是仅在将水果盛起并记录到餐桌上时才假。

You can use IF EXISTS to determine the presence of the row, and then use CASE WHEN to project this as the result you need, eg 您可以使用IF EXISTS确定行的存在,然后使用CASE WHEN将其投影为所需的结果,例如

Create procedure [dbo].[Craping_GetFruitCrapedOrNot]
(
    @FruitID int,
    @CrateID int,
    @FruitName varchar(100)
)
AS
  SELECT CASE WHEN EXISTS
  (
     SELECT     1
     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   

Do you mind if I ask a question: What is a Craped Fruit? 您介意我问一个问题:什么是绉果? ;) ;)

SqlFiddle here SqlFiddle在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM