Search code examples
sql-serverfunctionsql-server-2000table-functions

Is there a way to do a join with cases


Is there a way to make a join with cases?

Something like

select * from abba 
   case when a=b then 
      join acdc on abba.id=acdc.id
   when b=c then 
      join bebop on abba.id=bebop.id 
   end

Is there a way to do this?

Best regards Joe


Solution

  • The usual way to do this is to LEFT JOIN both tables and select the value based on the CASE condition:

    SELECT *, CASE WHEN a=b THEN acdc.myField ELSE bebop.myField END AS myField
      FROM abba 
           LEFT JOIN acdc ON abba.id=acdc.id 
           LEFT JOIN bebop ON abba.id=bebop.id