SQL Server: CASE statement in where clause

I am using SQL Server, how can I use a statement CASEin a statement in an whereSQL statement?

I want to rewrite this query:

select * 
from Persons P
where P.Age = 20
  and P.FamilyName in (select Name
                       from AnotherTable)

Using an operator CASE. I want the second condition

(P.FamilyName in ....)

executed only if CheckFamilyNametrue.

Something like that:

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 statements work CASEin SQL?

+4
source share
3 answers
where   P.Age = 20
        and 
        (
            not CheckFamilyName
            or
            P.FamilyName in (select Name From AnotherTable)
        )
+4
source

approach 1

select * 
from Persons P
where 1=1
    and P.Age = 20
    and (
        CheckFamilyName = 0
        or P.FamilyName in (select Name From AnotherTable)
    )

approach 2

select * 
from Persons P
where 1=1
    and P.Age = 20
    and CheckFamilyName = '0'
union all
select * 
from Persons P
where 1=1
    and P.Age = 20
    and CheckFamilyName = '1'
    and P.FamilyName in (select Name From AnotherTable)
+2
source

, (, , ) , :

select * 
from Persons P
join anothertable A on A.Name = P.FamilyName
where P.Age = 20

, select .

,

select * 
from Persons P
join anothertable A on A.Name = P.FamilyName and P.CheckFamilyName= true 
where P.Age = 20

, CheckFamilyName .

So we make it a left join.

select * 
from Persons P
left join anothertable A on A.Name = P.FamilyName and CheckFamilyName= true 
where P.Age = 20

This will contain lines where checkfamilyname is true, but the name does not exist - for checking those you can do as follows:

select * 
from Persons P
left join anothertable A on A.Name = P.FamilyName and CheckFamilyName= true 
where P.Age = 20 and (checkfamilyname = A.Name is not null)
0
source

Source: https://habr.com/ru/post/1622092/


All Articles