8

我有一个名为 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

4 回答 4

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 时要小心谨慎。这样做时,控制评估顺序的括号非常重要。

于 2008-12-09T16:48:05.440 回答
2

SQL 语句:

SELECT *  
FROM orders  
WHERE orderdate BETWEEN @startdate AND @enddate  
AND (@Closed = 1 OR CLosedDate IS NOT NULL)
于 2008-12-09T16:46:56.363 回答
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)
     )

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

祝你好运!

于 2008-12-09T16:48:32.773 回答
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))

双,可拆

于 2008-12-09T16:50:01.133 回答