我有三张桌子,
表1
Fruit_Crate_ID (varchar)
Fruit_Crate_Name (varchar)
Fruit_Crate_Size (varchar)
Fruit_Crate_Price (varchar)
表2
Fruit_Crate_ID (varchar)
Fruit_Eatable (Bool)
表3
Fruit_Crate_ID (integer)
Fruit_ID (integer)
Fruit_Eatable (Bool)
现在我需要创建一个首先检查的存储过程,
如果表2 可以食用或不通过检查 Fruit_Crate_ID ,如果它是假的,那么检查表3 ,就好像 Fruit_Crate_ID 和 Fruit_ID 可以食用或不食用。
USE [Database Name]
GO
CREATE PROCEDURE [dbo].[IsFruitEatable]
@Fruit_Crate_ID int,
@Fruit_ID int
AS
BEGIN
if ((select Fruit_Eatable from Table2
where Table1.Fruit_Crate_ID = @Fruit_Crate_ID))
{
select Fruit_Eatable from Table3
where Table3.Fruit_Crate_ID = @Fruit_Crate_ID and Table3.Fruit_ID = @Fruit_ID
}
更新
我必须首先检查表2,如果它说水果不可食用,那么无论水果ID如何,我都必须返回假。
但如果表2说水果箱可食用,那么我必须检查水果本身是否可以食用。
感谢
答案 0 :(得分:4)
您的查询包含2个错误:
exists
if
begin .. end
子句
醇>
这是正确的:
if exists (select Fruit_Eatable from Table2 where Table2.Fruit_Crate_ID = @Fruit_Crate_ID)
begin
select Fruit_Eatable from Table3
where Table3.Fruit_Crate_ID = @Fruit_Crate_ID and Table3.Fruit_ID = @Fruit_ID
end
已修改的查询
USE [Database Name]
GO
CREATE PROCEDURE [dbo].[IsFruitEatable]
@Fruit_Crate_ID int,
@Fruit_ID int
AS
BEGIN
declare @isEatable bit = null
if exists (select Fruit_Eatable from Table2 t2 where t2.Fruit_Crate_ID = @Fruit_Crate_ID and t2.Fruit_Eatable = 1)
begin
select @isEatable = Fruit_Eatable
from Table3 t3
where t3.Fruit_Crate_ID = @Fruit_Crate_ID and t3.Fruit_ID = @Fruit_ID
end
select isnull(@isEatable, 0) as IsFruitEatable