SQL条件在哪里

时间:2008-12-09 16:42:18

标签: sql conditional where

我有一个名为spGetOrders的存储过程,它接受一些参数:@startdate和@enddate。这会查询“订单”表。表中的一列称为“ClosedDate”。如果订单尚未关闭,则此列将保留NULL;如果订单尚未关闭,则此列将保留为日期值。我想添加一个@Closed参数,它将获取一些值。在一个简单的世界里,我能够做到......

select * from orders o
where o.orderdate between @startdate AND @enddate
and (if @Closed = 1 then o.ClosedDate IS NULL else o.ClosedDate IS NOT NULL)

显然,这不会起作用..我也在看动态sql,这是我最后的手段,但开始看起来像答案..

请帮助..

4 个答案:

答案 0 :(得分:14)

试试这个:

select * from orders o
where o.orderdate between @startdate AND @enddate
and ((@Closed = 1 And o.ClosedDate IS NULL) Or (@Closed = 0 And o.ClosedDate IS NOT NULL))

要注意在where子句中混合AND和OR。这样做时,用于控制评估顺序的括号非常重要。

答案 1 :(得分:2)

SQL语句:

SELECT *  
FROM orders  
WHERE orderdate BETWEEN @startdate AND @enddate  
AND (@Closed = 1 OR CLosedDate IS NOT NULL)

答案 2 :(得分:0)

或者这个:

select * from orders o
where o.orderdate between @startdate AND @enddate
and (  (@Closed = 1 AND o.ClosedDate IS NULL)
     OR (ISNULL(@Closed, 0) <> 1 AND o.ClosedDate IS NOT NULL)
     )

看起来您希望两个日期之间的所有订单都具有不一致的关闭信息。其他建议可能同样好(或更好),但我很确定这是有效的,并且对我来说是可读的(大多数其他建议在我打字时出现)。

祝你好运!

答案 3 :(得分:0)

基本上,写出来。

select * from orders o
where o.orderdate between @startdate AND @enddate
and ((@Closed = 1 and o.ClosedDate IS NULL)
    or (@Closed != 1 and o.ClosedDate IS NOT NULL))

加倍,可以删除