2014-08-28 39 views
0
Select * from order as o 
where (@datefrom is null or @dateto is null 
       or o.orderdate between @datefrom and @dateto)  
     or (@datefrom = o.orderdate) 

我想使用datefromdateto參數的日期範圍的選擇或我可以在datefrom參數類型日期等01.06.2014,在這種情況下datetonull具有兩個日期時間範圍參數,其中條件

這意味着我想爲兩個過濾器使用datefrom參數,但是當我在datefrom參數和dateto is null中輸入特定日期時,根據類型日期數據不正確。

請幫助解決這個問題。

回答

0

所以要清楚。如果輸入@datefrom@dateto,那麼您進行範圍檢查。如果只輸入@datefrom,則執行相等檢查。如果是的話,這應該工作:

select 
    * 
from 
    order o 
where (
    @dateto is not null and 
    o.orderdate between @datefrom and @dateto 
) or (
    @dateto is null and 
    o.orderdate = @datefrom 
) 

我在你的例子中注意到你也測試@fromdate爲null。這是否意味着什麼?

1

你的問題是,當@datefromnull,那麼整個where子句的值爲True的每一行 - 這樣的where條款沒有做任何事情。

這裏是實現你想要的東西的一種方式:

​​

請注意,我沒有用between,因爲它可真是曖昧和混亂的日期 - 見this article爲什麼。

0

像這樣的查詢將是動態的SQL這樣的事情更好的解決方案......

DECLARE @datefrom DATETIME = '20140101' 
DECLARE @dateto DATETIME = '20140303' 

DECLARE @Sql NVARCHAR(MAX); 

SET @Sql = N' Select * from [order] ' 
      + N' WHERE 1 = 1 ' 
      + CASE WHEN @datefrom IS NOT NULL 
        THEN N' AND orderdate >= @datefrom ' ELSE N' ' END 
      + CASE WHEN @dateto IS NOT NULL 
        THEN N' AND orderdate <= @dateto ' ELSE N' ' END 


EXECUTE sp_executesql @Sql 
        ,N'@datefrom DATETIME , @dateto DATETIME' 
        ,@datefrom 
        ,@dateto 
相關問題