2017-09-28 117 views
0

我發現了一堆類似的questions,我有,但無法得到確切的答案!如何在SQL where條款中應用if條件的用戶過濾器?

我有以下SQL中的條件where子句

declare @status int, @applyUserFilter bit, @user nvarchar(156) 

--following are values being set by UI 
set @activeStatus = 1 
set @applyUserFilter = 1 
set @user = 'xyzUser' 

--I want to filter the list by users only when @applyUserFilter flag is true otherwise it should return the list for all users 

--This is what i tried but gives syntax error 
WHERE ActiveStatus = @activeStatus 
     AND CASE WHEN @applyUserFilter = 1 THEN User = @user 

注:這隻能說明where子句代碼!

+0

使用'CASE'在'WHERE'聲明要求你設置一個'column'等於'CASE'的結果。所以當場景'@applyUserFilter = 1'爲真時,需要將一列設置爲等於1來進行過濾。 – Simon

+0

我想你想要實現的是:'User = CASE WHEN @applyUserFilter = 1 then @user else null end' else'else'語句是可選的。 – Simon

+0

謝謝! @Simon在這種情況下,當'@applyUserFilter = 0'時它不會返回任何東西,在這種情況下,我希望它返回所有用戶的完整列表 – updev

回答

0

什麼:

WHERE [email protected] 
    AND (user IN (SELECT user from #users) AND @applyUserFilter=0 
    OR [email protected]) 
+0

這給我只有總是傳遞的用戶列表! – updev

+0

爲我工作;)http://sqlfiddle.com/#!6/67f3c/3/0 –