views:

219

answers:

4
@FromDate datetime = null
@ToDate datetime = null

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

When any date is null, the records are not displayed. What is the correct syntax so that I can get all records if any of the dates are null.

I have thought of this:

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

Thanks.

+2  A: 

Try something like

SELECT * FROM TABLE 
WHERE .... 
AND [PI].Date BETWEEN ISNULL(@FromDate, [PI].Date) AND ISNULL(@ToDate, [PI].Date)
astander
I don't think an index will be used because the way you are doing it.
KM
@KM: Can you please elaborate?
Aseem Gautam
@Aseem Gautam, with a query like mine, the range is a fixed constant for every row that can be resolved and planned for by sql server, but the range in this query can be different for each row (because of the use of `[PI].Date` in the `ISNULL()`s). This query will NEVER use an index. My version can use an index. continued...
KM
...For example, if the date column is a clustered PK and you have a large table and return only a few rows, my version will use the index and this query will not. but if the table is small or the rows returned are a high percentage of the total table, no index will be used. In any case this will never use an index and mine will sometimes.
KM
+1  A: 

You can try something like this:

@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

Raja
+1  A: 

you can always default the date values to some extreme value and make sure an index is used:

SELECT 
    * 
    FROM TABLE 
    WHERE .... 
        AND [PI].Date BETWEEN ISNULL(@FromDate,convert(datetime,'1/1/1800'))
                          AND ISNULL(@ToDate, convert(datetime,'1/1/2500'))
KM
A: 
SELECT * FROM [PI]
WHERE ([PI].Date >= @FromDate OR @FromDate IS NULL)
AND ([PI].Date <= @ToDate OR @ToDate IS NULL)
Anthony Faull