Skip to content
Advertisement

Conditional Inner Join with two Functions

I have two functions. I need to decide whether to join with these two based on a BIT Value.

ON APEL.data_Period_dataination_Lookup_ID = CCEL.data_Period_dataination_Lookup_ID
INNER JOIN  markcommon.GetPredecessordatadataIds() AS PIDS
IF @Combined_Flag=1 
BEGIN
ON PIDS.data_Period_dataination_Identifier = APEL.data_Period_dataination_Identifier
AND PIDS.data_Period_Identifier = APL.data_Period_Identifier
END

Basically

if BIT=0 join with function 1 else join with function 2

I tried putting an IF Clause .. but it does not seem to work. What is the proper way to do it?

Advertisement

Answer

Just add your static condition as part of the join condition and use a LEFT JOIN to ensure it works with the missing row. You can then use a case expression in your select to obtain the correct column e.g.

SELECT

    CASE WHEN F1.id IS NOT NULL THEN F1.MyColumn ELSE F2.MyColumn END

FROM ...

LEFT JOIN markcommon.Function1() AS F1
  ON @Combined_Cohort = 1
  AND {The rest of the join conditions}

LEFT JOIN markcommon.Function2() AS F2
  ON @Combined_Cohort = 0
  AND {The rest of the join conditions}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement