Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all records if parameter is null

Tags:

sql-server

The following is my SP:

Alter PROCEDURE GetList 
(

@FromDate date = null,
@ToDate date = null

)
AS

Select * FROM CallList c
Where c.CallDate > @FromDate and c.CallDate < @ToDate 

If there was no passed date filter, I want to get all the records.

How would I do it?

like image 333
Ezi Avatar asked May 25 '11 22:05

Ezi


2 Answers

You can do this:

SELECT * FROM CallList c
WHERE (c.CallDate > @FromDate OR @FromDate IS NULL) AND 
      (c.CallDate < @ToDate OR @ToDate IS NULL)

This also leaves you open to the possibility to leaving one of the dates null and not the other.

like image 195
Colin Mackay Avatar answered Oct 01 '22 18:10

Colin Mackay


you'd do the following

SELECT * 
FROM CallList AS C
WHERE (@FromDate IS NULL OR c.CallDate > @FromDate)
AND (@ToDate IS NULL OR c.CallDate < @ToDate)
like image 28
Nathan Tregillus Avatar answered Oct 01 '22 20:10

Nathan Tregillus