SQL - If Param Null then omit criteria in WHERE clause

77 views Asked by At
@TimeCurr Char(1)

SELECT RecordDate, a, b,c
FROM tbl_xyz
WHERE 1 = 1
AND

if @TimeCurr = 'Y' Then RecordDate = GetDate()

if @TimeCurr = 'N' then RecordDate <= GetDate()

if @TimeCurr = Null then omit the critera altogether. How can we accomplish this?

1

There are 1 answers

0
Gordon Linoff On

Something like this:

SELECT RecordDate, a, b,c
FROM tbl_xyz
WHERE 1 = 1 AND
      ((@TimeCurr = 'Y' AND RecordDate = CAST(GetDate() as date)) OR
       (@TimeCurr = 'N' AND RecordDate <= GetDate()) OR
       @TimeCurr IS NULL
      );

Based on the use of GETDATE(), I am guessing that you are using SQL Server. If so, the function GETDATE() returns a date/time value. You don't usually want to use = with it. That is why I convert it to a date, assuming that RecordDate is actually a date with no time component.