SQL Conditional Where

后端 未结 4 1256
借酒劲吻你
借酒劲吻你 2020-12-20 17:41

I have a Stored Procedure called spGetOrders which accepts a few parameters: @startdate and @enddate. This queries an \"Orders\" table. One of the columns in the table is

相关标签:
4条回答
  • 2020-12-20 18:16

    Try this:

    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))
    

    Be vary careful about mixing AND's and OR's in the where clause. When doing this, the parenthesis to control the order of evaluation is VERY important.

    0 讨论(0)
  • 2020-12-20 18:19

    Basicly, write it out.

    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))
    

    double, can be removed

    0 讨论(0)
  • 2020-12-20 18:30

    SQL Statement:

    SELECT *  
    FROM orders  
    WHERE orderdate BETWEEN @startdate AND @enddate  
    AND (@Closed = 1 OR CLosedDate IS NOT NULL)
    
    0 讨论(0)
  • 2020-12-20 18:31

    Or this:

    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)
         )
    

    It looks like you want all the orders between two dates that have inconsistent Close information. The other suggestions are probably as good (or better) but I'm pretty sure that this works and is readable to me (most of the other suggestions appeared as I was typing).

    Good luck!

    0 讨论(0)
提交回复
热议问题