Skip to content
Advertisement

Sql conditional Join statement

I have this sample

SELECT 
      Lookup_TypeTraveaux_OT.Designation
      ,[QTE]
      ,Machines.NomMachine
      ,Equipements.Nom
      ,[Autres]
  FROM ASS_OT_Traveaux INNER JOIN Lookup_TypeTraveaux_OT ON EXISTS(SELECT Lookup_TypeTraveaux_OT.Id 
                       INTERSECT 
                       SELECT ASS_OT_Traveaux.TypeTraveaux)
                       INNER JOIN Machines ON EXISTS(SELECT Machines.NumMachine 
                       INTERSECT 
                       SELECT ASS_OT_Traveaux.CodeMachine)
                       INNER JOIN Equipements ON Equipements.NumEquipement = 
                       case when
                       ASS_OT_Traveaux.CodeEquipement is not null then ASS_OT_Traveaux.CodeEquipement
                       end
where NumOt = 1

I want to code this case in sql :

if(!ASS_OT_Traveaux.CodeEquipement.IsNull()){
// Do the join else i dont join it
}

When i have a null value in “ASS_OT_Traveaux.CodeEquipement” it doesnt show any data enter image description here

Advertisement

Answer

SELECT 
      Lookup_TypeTraveaux_OT.Designation
      ,[QTE]
      ,Machines.NomMachine
      ,Equipements.Nom
      ,[Autres]
  FROM ASS_OT_Traveaux 
left JOIN Lookup_TypeTraveaux_OT ON Lookup_TypeTraveaux_OT.Id = 
case when
ASS_OT_Traveaux.TypeTraveaux is not null then ASS_OT_Traveaux.TypeTraveaux
end
left JOIN Machines ON Machines.NumMachine = 
case when
ASS_OT_Traveaux.CodeMachine is not null then ASS_OT_Traveaux.CodeMachine
end
left JOIN Equipements ON Equipements.NumEquipement = 
case when
ASS_OT_Traveaux.CodeEquipement is not null then ASS_OT_Traveaux.CodeEquipement
end
where NumOt = 1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement