I am joining a few tables in the SELECT statement like below and it has three parameters.
DECLARE @Jobid INT=0,
@leadid INT=0,
@employeeid INT=0
SELECT e.id,
l.id,
j.id,
e.NAME,
l.NAME,
j.NAME
FROM employee e
INNER JOIN leads l
ON e.leadid = l.id
INNER JOIN Jobs j
ON j.id = e.Jobid
This works fine without filtering.
In the WHERE clause I have to add something like below. If any of the three ID's is greater than zero then I have to consider the filter in the WHERE clause; if it is equal to zero I won't consider that particular condition.
If @jobid> 0
then introduce this condition in where clause (j.id=@jobid)
If @leadid> 0
then introduce this condition in where clause (l.id=@leadid)
If @employeeid> 0
then introduce this condition in where clause (e.id=@employeeid)
I know how to achieve this through dynamic SQL but I need a static SQL statement to achieve this.
I tried the following:
where
((J.Id = @Jobid and @Jobid>0 )
or @Jobid=0)
and (
(L.Id = @leadid and @leadid>0 )
or @leadid=0
)
and (
(e.Id = @employeeid and @employeeid >0 )
or @employeeid =0
)
But there is a performance hit.
Kindly suggest me any other better way of doing this in static SQL especially using Case When
.