我有一个存储过程,它根据特定条件返回1或0的整数。它目前使用三个select语句,它将被多个位置的多个用户大量使用。必须有一种更有效的方法来做到这一点。
简而言之,查询首先检查订单上的所有清单项是否都已完成(单独的表),然后检查查看名为BreakOutGuest(位域)的字段是1还是0.取决于结果它检查总客人数是否大于0且订单总数为零。它会在所有这些条件上返回1或0。有没有更有效的方法来做到这一点?一个临时表所以我只需要打一次实际的表吗?以下是代码。
@ORDERID INT
AS
BEGIN
DECLARE @AUTO_CLOSE INT
SET NOCOUNT ON;
--If all checklist items are marked complete move on, if not set @AUTO_CLOSE=0
IF NOT EXISTS(SELECT ORDERID FROM dbo.orderchecklistitems WHERE OrderID=@ORDERID AND CompletedON IS NULL)
BEGIN
--if BreakOutGuestFees is 1 only sum Guest_Count_1 + Guest_Count_2
IF EXISTS(SELECT * FROM dbo.Orders WHERE (GuestCount_1 + GuestCount_2)>1 AND OrderTotal=0 AND BreakoutGuestFees=1)
BEGIN
SET @AUTO_CLOSE=1
END
ELSE
SET @AUTO_CLOSE=0
--if BreakOutGuestFees is 0 only consider Guest_Count_1
IF EXISTS(SELECT * FROM dbo.Orders WHERE (GuestCount_1)>1 AND OrderTotal=0 AND BreakoutGuestFees=0)
BEGIN
SET @AUTO_CLOSE=1
END
ELSE
SET @AUTO_CLOSE=0
END
ELSE
SET @AUTO_CLOSE=0
END
答案 0 :(得分:2)
如果没有错,您可以使用if
,if
逻辑将两个AND
子句合并到单个OR
子句中。试试这个。
IF NOT EXISTS(SELECT ORDERID
FROM dbo.orderchecklistitems
WHERE OrderID = @ORDERID
AND CompletedON IS NULL)
BEGIN
IF EXISTS(SELECT *
FROM dbo.Orders
WHERE ( ( GuestCount_1 + GuestCount_2 > 1
AND BreakoutGuestFees = 1 )
OR ( BreakoutGuestFees = 0
AND GuestCount_1 > 1 ) )
AND OrderTotal = 0
AND OrderID = @ORDERID)
SET @AUTO_CLOSE=1
ELSE
SET @AUTO_CLOSE=0
END
ELSE
SET @AUTO_CLOSE=0
答案 1 :(得分:1)
您只需一个查询即可执行选择检查
SELECT
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT ORDERID FROM dbo.orderchecklistitems WHERE OrderID=@ORDERID AND CompletedON IS NULL)),
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT 1 FROM dbo.Orders WHERE (GuestCount_1 + GuestCount_2)>1 AND OrderTotal=0 AND BreakoutGuestFees=1)),
(SELECT sum(1) FROM dual WHERE EXISTS (SELECT 1 FROM dbo.Orders WHERE (GuestCount_1)>1 AND OrderTotal=0 AND BreakoutGuestFees=0))
INTO
result1, result2, result3
from dual
然后检查结果
答案 2 :(得分:1)
DELCARE @AUTO_CLOSE INT = 0
IF NOT EXISTS(SELECT ORDERID
FROM dbo.orderchecklistitems
WHERE OrderID = @ORDERID
AND CompletedON IS NULL)
BEGIN
SET @AUTO_CLOSE =
(
SELECT
CASE
WHEN (GuestCount_1 + GuestCount_2 > 1) AND BreakoutGuestFees = 0 THEN 1
WHEN (GuestCount_1 > 1 ) AND BreakoutGuestFees = 1 THEN 1
ELSE 0 END
FROM dbo.orders
WHERE OrderTotal = 0 AND OrderID = @orderID
)
END