SQL日期选择为NULL,After,Before,Between

时间:2012-01-24 16:18:57

标签: sql sql-server-2008

要求:按日期选择为After,Before,Between或all if 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;
    

3 个答案:

答案 0 :(得分: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')

修改

这两种方法之间的执行计划可能存在差异,因此您可以尝试这两种方法,看看是否有一种方法胜过另一种方法......

答案 1 :(得分:0)

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

答案 2 :(得分: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)

考虑所有情况。