Reputation: 3
I am attempting to build a simple lookup table that will have its own web page display. I am providing simple search variables, and one of those variables is Status. I am looking for them to be able to Choose from Active, Inactive, or both, I am looking to easily look for both at once. There are other status in the database such as 'D' for a soft delete that I do not want returned at all.
Declare @stat nvarchar(5) = 3
Select [Status]
from tableUser
where [Status] in (CASE @stat
WHEN 1 THEN 'A'
WHEN 2 THEN 'I'
WHEN 3 THEN 'A','I'
END)
The above is what I have tried.
Upvotes: 0
Views: 58
Reputation: 415630
You want the CASE
statement to produce an expression, but that's not how it works. CASE
statements produce values (which can be included as expressions, but the expressions must still reduce to values at query compile time). 'A','I'
does not reduce to a value, so you cannot use it as the result of a CASE
statement.
Instead, write the condition more like this:
WHERE 1 = CASE WHEN @stat = 1 AND [Status] = 'A' THEN 1
WHEN @stat = 2 AND [Status] = 'I' THEN 1
WHEN @stat = 3 AND [Status] IN ('A', 'I') THEN 1
ELSE 0 END
or remove the CASE
expressions and build all that directly into the WHERE
clause:
WHERE ( (@stat = 1 AND [Status] = 'A')
OR (@stat = 2 AND [Status] = 'I')
OR (@stat = 3 AND [Status] IN ('A', 'I'))
)
Upvotes: 0
Reputation: 1269523
Just use boolean logic:
WHERE (@stat IN (1, 3) AND Status = 'A') OR
(@stat IN (2, 3) AND Status = 'I')
Upvotes: 2