2012-01-24 86 views
4

要求:通過日期後選擇,之前,之間或全部,如果空SQL日期選擇爲NULL,之後,之前,之間

我使用的是SQL Server 2008中

這是我的嘗試,但我對於在案例之外有效使用的代碼,會出現語法錯誤。

  1. 有沒有更好的方法?
  2. 用例什麼是正確的語法?

    declare @StartDate datetime;  
    declare @EndDate datetime; 
    SET @EndDate = GETDATE(); 
    SET @StartDate = DATEADD(year, -2, GETDATE()); 
    
    select * 
    from ArCustomer 
    where CAST(Customer as int) > 1000 
    AND 
        CASE WHEN @StartDate IS NOT NULL AND @EndDate IS NOT NULL THEN 
         ArCustomer.DateLastSale BETWEEN @StartDate AND @EndDate 
        WHEN @StartDate IS NULL AND @EndDate IS NOT NULL THEN 
         ArCustomer.DateLastSale < @EndDate 
        WHEN @StartDate IS NOT NULL AND @EndDate IS NULL THEN 
         ArCustomer.DateLastSale > @StartDate   
    END; 
    

回答

6

另外,還可以不受日期限制參數,如果它是NULL

SELECT * 
FROM ArCustomer ac 
WHERE 
    CAST(ac.Customer as int) > 1000 
    AND (ac.DateLastSale >= @StartDate OR @StartDate IS NULL) 
    AND (ac.DateLastSale <= @EndDate OR @EndDate IS NULL) 

或者......你可以把它當作低端處理NULL或高端日期:

SELECT * 
FROM ArCustomer ac 
WHERE 
    CAST(ac.Customer as int) > 1000 
    AND ac.DateLastSale BETWEEN ISNULL(@StartDate, '1900-01-01') 
     AND ISNULL(@EndDate, '9999-12-31') 

編輯:

有可能是這兩種方法之間的執行計劃的不同,所以你可以嘗試這兩種方法,看看一個外執行等...

+0

謝謝,看起來像那樣(選項1),比我的嘗試更優雅。 – GBrookman

0
WHERE CAST(Customer as int) > 1000 AND 
    (@StartDate IS NULL OR @StartDate <= ArCustomer.DateLastSale) AND 
    (@EndDate IS NULL OR ArCustomer.DateLastSale <= @EndDate) 
0

請請注意,下面的查詢應該被避免,並且應該提及特定的列名。

declare @StartDate datetime;  
declare @EndDate datetime; 
SET @EndDate = GETDATE(); 
SET @StartDate = DATEADD(year, -2, GETDATE()); 

Declare @SQL Varchar(1000) 

Set @SQL = 'select ColumnName 
from ArCustomer 
where CAST(Customer as int) > 1000 
AND' 
if(@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
Begin 
    Set @SQL = @SQL + ' ArCustomer.DateLastSale BETWEEN ''' + Convert(varchar, @StartDate) + 
    ''' AND ''' + Convert(varchar, @EndDate) + '''' 
End 
else if(@StartDate IS NULL AND @EndDate IS NOT NULL) 
Begin 
     Set @SQL = @SQL + ' ArCustomer.DateLastSale < ''' + Convert(varchar, @EndDate) + '''' 
End 
else 
    Set @SQL = @SQL + ' ArCustomer.DateLastSale > ''' + Convert(varchar, @StartDate) + ''''   


exec(@SQL) 

考慮所有情況。