我發現了一堆類似的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子句代碼!
使用'CASE'在'WHERE'聲明要求你設置一個'column'等於'CASE'的結果。所以當場景'@applyUserFilter = 1'爲真時,需要將一列設置爲等於1來進行過濾。 – Simon
我想你想要實現的是:'User = CASE WHEN @applyUserFilter = 1 then @user else null end' else'else'語句是可選的。 – Simon
謝謝! @Simon在這種情況下,當'@applyUserFilter = 0'時它不會返回任何東西,在這種情況下,我希望它返回所有用戶的完整列表 – updev