这是在 sql server 2005 中。我有两个表:customers
和orders
. 有一个存储过程有一个参数minimumorders
(0 或大于零是可能的值)。我想避免IF ELSE
像上面那样的块并使用CASE
声明。有没有办法可以CASE
在WHERE
子句中使用语句来避免IF ELSE
代码中的块?目前IF
&ELSE
块上的 5 行重复。我不希望他们重复。我期待着像下面这样的查询。
CREATE PROC STOREDPROC1
@MinimumOrders INT AS IF @MinimumOrders = 0
BEGIN
SELECT
CUSTOMERID
, (SELECT COUNT(ORDERID) FROM ORDERS O WHERE O.CUSTOMERID = C.CUSTOMERID) AS ORDERS
FROM CUSTOMER C
ENDELSE IF @MinimumOrders = 1
BEGIN
SELECT
CUSTOMERID
, (SELECT COUNT(ORDERID) FROM ORDERS O WHERE O.CUSTOMERID = C.CUSTOMERID) AS ORDERS
FROM CUSTOMER C
WHERE (SELECT COUNT(ORDERID) FROM ORDERS O WHERE O.CUSTOMERID = C.CUSTOMERID) > 0
END
我需要一些CASE
如下声明。不幸的是,它对我不起作用。
-------------------- 12/20/2011 -- 11:52:34 AM -- Tuesday --------------------
SELECT
CUSTOMERID
, (SELECT COUNT(ORDERID) FROM ORDERS O WHERE O.CUSTOMERID = C.CUSTOMERID) AS ORDERS
FROM CUSTOMER C
AND C.customerid=
CASE @MiniumOrders
WHEN 0 THEN C.CustomerID
WHEN 1 THEN
CASE ( Select COUNT(O.CustomerID) FROM Orders O where O.Customerid = C.customerid )
WHEN 0 THEN 0 -- customer id = 0 means no match
ELSE C.CustomerID
END
END
-------------------- 12/20/2011 -- 11:52:34 AM -- Tuesday --------------------