Any ideas how I can create a join on a table retrieved from data in a previously joined table? For example, I have an objects table that contains existing table Names, the display field of those tables, and the main ID field of those tables. I want to join on the table specified in the objects table as well as the objects table.
select T.field1,T.field2,T.field3,O.DisplayName
from tableT as T
inner join objects as O on T.SystemObjectID = O.SystemObjectID
inner join O.TableName as X on X.O.ID = T.SystemObjectRecordID
I understand the script above is not correct. But what is the easiest most efficient way of accomplishing this task? I hope I’m clear on what I’m asking…
Thank you for any help in advance.
You can’t do that.
What you can do is take the results of that and create a string that is a SQL query.
You can even make that query parameterised and execute it using sp_executesql.
– That link has a few good examples to get you started.
This is because SQL is compiled to an execution plan before it is executed. At this point in time it needs to know the tables, decides the indexes to use, etc.
This means that data is data and sql is sql. You can’t use late binding scripting tricks to modify the query that is already running.
You’re stuck with SQL that writes SQL (Dynamic SQL) I’m afraid.