J'utilise SQL Server, comment puis-je utiliser une instruction CASE
dans une clause where
dans une instruction SQL?
Je veux réécrire cette requête:
select * from Persons P where P.Age = 20 and P.FamilyName in (select Name from AnotherTable)
En utilisant une déclaration de case
. Je le veux donc la deuxième condition
(P.FamilyName in ....)
est exécuté uniquement si CheckFamilyName
est true.
Quelque chose comme ça:
select * from Persons P where P.Age = 20 case when CheckFamilyName= true then and P.FamilyName in ( select Name From AnotherTable) else end
Comment fonctionnent les instructions de case
dans SQL?
where P.Age = 20 and ( not CheckFamilyName or P.FamilyName in (select Name From AnotherTable) )
approche 1
select * from Persons P where 1=1 and P.Age = 20 and ( CheckFamilyName = 0 or P.FamilyName in (select Name From AnotherTable) )
approche 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)
Tout d'abord vous pouvez (et devriez probablement) utiliser une jointure pour votre premier cas comme ceci:
select * from Persons P join anothertable A on A.Name = P.FamilyName where P.Age = 20
Il convient de noter que cette déclaration ne vous donnera que des résultats avec ce nom de famille.
Donc, quand vous ajoutez à votre nouvelle condition
select * from Persons P join anothertable A on A.Name = P.FamilyName and P.CheckFamilyName= true where P.Age = 20
Vous obtiendrez seulement des résultats où CheckFamilyName est vrai.
Nous faisons donc une jointure à gauche.
select * from Persons P left join anothertable A on A.Name = P.FamilyName and CheckFamilyName= true where P.Age = 20
Cela inclura des lignes où checkfamilyname est vrai mais le nom n'existe pas – pour valider ceux que vous pouvez faire ce qui suit
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)