You cannot make a conditional join this way.
You can just do a regular LEFT JOIN. If no rows match the join criteria, these columns will be NULL:
Select * from table a left Join table b on a.id = b.id left Join table c on a.id = c.id left Join table d on a.id = d.id
Columns b. * may be NULL or c columns. * may be NULL or columns d. * may be NULL.
If you need to select the first non-NULL column, use COALESCE:
Select *, COALESCE(b.SOMECOLUMN, c.SOMECOLUMN, d.SOMECOLUMN) AS SOMECOLUMN from table a left Join table b on a.id = b.id left Join table c on a.id = c.id left Join table d on a.id = d.id
As commentators note, if the tables do not exist, this will not work. I think that I would really advocate for the promotion and creation of tables so that your schemes always meet expectations. Dynamic SQL is a pain to maintain and debug, and static SQL and schemas can be queried to ensure that they meet expectations using metadata (i.e. a procedure or view will not be valid if the table is missing, and dependencies can be viewed explicitly )
source share