Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query date null check

Tags:

sql

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 

If @startDate AND @endDate are both null then I want it to return the rows ignoring the date check in the where clause.

How?

like image 303
Riain McAtamney Avatar asked Dec 28 '22 11:12

Riain McAtamney


2 Answers

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

like image 73
David Hedlund Avatar answered Jan 04 '23 23:01

David Hedlund


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 ) 
like image 34
IordanTanev Avatar answered Jan 04 '23 23:01

IordanTanev