tags:

views:

49

answers:

4

Hi,

I have the following stored procedure.

ALTER PROCEDURE [dbo].[spList_Report] 
  @id INT, 
  @startDate DATETIME = NULL, 
  @endDate DATETIME = NULL, 
  @includeStatus1 BIT, 
  @includeStatus2 BIT, 
  @includeStatus3 BIT, 
  @includeStatus4 BIT 

AS 
  SET NOCOUNT ON 

  SELECT * 
  FROM 
    tblProducts as products 
  WHERE  
    product.intID = @id 
    AND product.dateMain >= @startDate  
    AND product.dateMain <= @endDate 

I know this probably seems like a silly question but if @startDate AND @endDate are both null then I want it to return the rows ignoring the date check in the where clause.

Any help would be greatly appreciated.

+5  A: 

This should do

AND product.dateMain >= ISNULL( @startDate, 0)
AND product.dateMain <= ISNULL( @endDate, product.dateMain + 1)

ISNULL yields the second value, if the first value is null.

Thus:

if @startDate is null, then dateMain must be bigger than 0 (1900-01-01)

if @endDate is null, then dateMain must be smaller than dateMain + 1 day

David Hedlund
+1. Same as my (deleted) answer only better :)
Lieven
Thanks, works perfect
Zaps
+2  A: 

Hi, you can try something like this

ALTER PROCEDURE [dbo].[spList_Report] 
  @id INT, 
  @startDate DATETIME = NULL, 
  @endDate DATETIME = NULL, 
  @includeStatus1 BIT, 
  @includeStatus2 BIT, 
  @includeStatus3 BIT, 
  @includeStatus4 BIT 

AS 
  SET NOCOUNT ON 

  SELECT * 
  FROM 
    tblProducts as products 
  WHERE  
    product.intID = @id 
    AND product.dateMain >= ISNULL( @startDate, product.dateMain )  
    AND product.dateMain <= ISNULL( @endDate,  product.dateMain ) 
IordanTanev
A: 

You can utilize an "or" in your Sql, but since this is a stored procedure:

If @startdate is null Or @enddate is null
   begin
      select without using a date range
   end
Else
   begin
      select using date range
   end
Kris Krause
that's a lot of duplication, though, for something for which there are simpler solutions (Lieven, IordanTanev and me all getting at the same solution)
David Hedlund
A: 

I would use Kris Krause's solution, but change the "IF" statement to use "AND". I think if you use the first two solutions the query engine may perform a table/index scan on the date fields. You want to keep your queries as concise as possible for best performance, so don’t run queries on unnecessary columns.

IF @startdate IS NULL AND @enddate IS NULL
BEGIN
    SELECT * FROM tblProducts as products WHERE  
    product.intID = @id 
END
ELSE
BEGIN
    SELECT * FROM tblProducts as products WHERE  
    product.intID = @id 
    AND product.dateMain >= @startDate  
    AND product.dateMain <= @endDate 
END
Ryan Leyesa