sql server可选参数:between子句的语法

时间:2010-04-15 17:09:07

标签: sql-server tsql

@FromDate datetime = null
@ToDate datetime = null

SELECT * FROM TABLE
WHERE ....
AND [PI].Date BETWEEN @FromDate AND @ToDate

如果任何日期为空,则不显示记录。正确的语法是什么,以便在任何日期为空时我可以获取所有记录。

我想到了这个:

@FromDate datetime = '01/01/1901',
@ToDate datetime = '12/31/9999'

感谢。

4 个答案:

答案 0 :(得分:4)

尝试类似

的内容
SELECT * FROM TABLE 
WHERE .... 
AND [PI].Date BETWEEN ISNULL(@FromDate, [PI].Date) AND ISNULL(@ToDate, [PI].Date)

答案 1 :(得分:2)

您始终可以将日期值默认为某个极值,并确保使用索引:

SELECT 
    * 
    FROM TABLE 
    WHERE .... 
        AND [PI].Date BETWEEN ISNULL(@FromDate,convert(datetime,'1/1/1800'))
                          AND ISNULL(@ToDate, convert(datetime,'1/1/2500'))

答案 2 :(得分:1)

您可以尝试这样的事情:

@FromDate datetime = null
@ToDate datetime = null

SELECT * FROM TABLE
WHERE ....
AND [PI].Date BETWEEN CASE WHEN @FromDate is null THEN '01/01/1901' ELSE @FromDate END AND 
CASE WHEN @ToDate is null THEN '12/31/9999' ELSE @ToDate END

HTH

答案 3 :(得分:1)

SELECT * FROM [PI]
WHERE ([PI].Date >= @FromDate OR @FromDate IS NULL)
AND ([PI].Date <= @ToDate OR @ToDate IS NULL)