我在下面的SELECT語句中加入了幾個表,它有三個參數。在WHERE子句中應用條件過濾
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
這工作正常,沒有過濾。
在WHERE子句中,我必須添加如下所示的內容。如果三個ID中的任何一個大於零,那麼我必須考慮WHERE子句中的過濾器;如果它等於零,我不會考慮這個特定的條件。
If @jobid> 0
then introduce this condition in where clause ([email protected])
If @leadid> 0
then introduce this condition in where clause ([email protected])
If @employeeid> 0
then introduce this condition in where clause ([email protected])
我知道如何通過動態SQL來實現這一點,但我需要一個靜態SQL語句來實現這一點。
我試過如下:
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
)
但是有一個性能命中。
請在靜態SQL中建議我使用其他更好的方法,特別是使用Case When
。
選中此問題[答案](http://stackoverflow.com/questions/34730633/how-to-add-to-where-clause-depending-on-parameter-value/34730678#34730678)。 –
只要'(J.Id = @Jobid或@ Jobid = 0)'等也會做同樣的事情。 (不知道它是否會更快,但...) – jarlh
@Mihail:我不是在尋找動態SQL – StackUser