-1

I am trying to create a query where when you do not input value in @date variable it will show result in SQL.

declare @Holiday varchar(50), @Date date
set @holiday = null
set @date = null

Select *
from tbl_Holiday
where Holiday like '%' + isnull(@Holiday,'') + '%'
and HDate = @Date

The above codes are the one I'm using. When I comment the last line of code it works fine, but I need to find a way to use the date for searching. Thank you for future responses.

EzLo
  • 13,780
  • 10
  • 33
  • 38

4 Answers4

0

There're a few ways to do it. I'd keep it simple:

declare @Holiday varchar(50), @Date integer
set @holiday = Null
set @Date = Null

IF @Date !='' or @Date is NOT NULL
    BEGIN
        Select *
        from tbl_Holiday
        where Holiday like '%' + isnull(@Holiday,'') + '%'
        and HDate = @Date
    END
ELSE 
BEGIN
        Select TOP (5)*
        from tbl_Holiday
END 
BI Dude
  • 1,842
  • 5
  • 37
  • 67
0

Use an OR to check for NULL for @Date.

where 
    (@Holiday IS NULL OR Holiday like '%' + @Holiday + '%') and 
    (@Date IS NULL OR HDate = @Date)

Whenever supplied @Date is NULL, condition will result to true and the other @Date filter won't apply.

Using this trick multiple times on the same query (multiple optional filters) will have impact on performance due to poor plan execution. If you need performance please read this thread about optimization.

EzLo
  • 13,780
  • 10
  • 33
  • 38
0

If you care about optimization (i.e. the use of indexes) then separate queries or dynamic SQL are probably the better choice.

But if you want to just express the logic in a single query, then I would recommend CONCAT() for the holiday piece and then an explicit NULL comparison:

Select *
from tbl_Holiday
where Holiday like concat('%', @Holiday, '%') and
      (@Date is null or HDate = @Date);

Unlike +, concat() simply ignores NULL values, which is convenient in this case.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can use ISNULL also with your @Date variable:

declare @Holiday varchar(50), @Date date
set @holiday = null
set @date = null

SELECT  *
FROM    tbl_Holiday
WHERE   Holiday like '%' + ISNULL(@Holiday,'') + '%'
AND     HDate = ISNULL(@Date, HDate)
Yair Maron
  • 1,860
  • 9
  • 22