I'm using SQL Server, how do I use a CASE
statement within a where
clause in a SQL statement?
I want to rewrite this query:
select *
from Persons P
where P.Age = 20
and P.FamilyName in (select Name
from AnotherTable)
Using a case
statement. I want it so the second condition
(P.FamilyName in ....)
is executed only if CheckFamilyName
is true.
Something like this:
select *
from Persons P
where P.Age = 20
case when CheckFamilyName= true
then
and P.FamilyName in (
select Name
From AnotherTable)
else
end
How do case
statements in SQL work?
CASE
in T-SQL is an expression (likea+b
) - NOT a statement.CASE
can return a single, atomic value - it cannot be used to conditionally execute code fragments or code paths.