Is a "dynamic" SQL join possible?

I have an Action table with a structure (part) like this:

Action : ActionTypeID, ActionConnectionID ...

ActionTypeID refers to types 1-5 that correspond to different tables (1 = Pro, 2 = Project, etc.). ActionConnectionID is primaryKey in the corresponding table;

i.e. ActionTypeID = 1, ActionConnectionID = 43 β†’ will point to Pro.ProID = 43 and ActionTypeID = 2, ActionCynectionID = 23 β†’ will point to Project.ProjectID = 233

Is there a way to "dynamically join different tables depending on the value in the ActionTypeID column? That is. For records with ActionTypeID = 1 this would be:

Select Action.* 
From Action Left Join Pro On Action.ActionConnectionID=Pro.ProID

for records with ActionTypeID = 2 this would be:

Select Action.* 
From Action Left Join Project On Action.ActionConnectionID=Project.ProjectID

and etc.

, ActionTypes , - , : -)

+3
2

- :

Select Action.*  
From   Action 
       Left Join Pro 
             ON Action.ActionConnectionID=Pro.ProID and ActionTypeID=1
       Left Join Project 
             ON Action.ActionConnectionID=Project.ProjectID and ActionTypeID=2

, sql, .

+2

- ? , , " , ", . , ? , Pro, Project .. - ? , , ( ). UNION, .

(Select Action.* 
From Action Left Join Pro On Action.ActionConnectionID=Pro.ProID)
UNION
(Select Action.* 
From Action Left Join Project On Action.ActionConnectionID=Project.ProjectID)
+2

Source: https://habr.com/ru/post/1744786/


All Articles