0

I have 3 tables all related to chain by foreign keys

Table1: 
ID 
name
--------
Table2: 
ID 
name 
T1_ID
------
Table3: 
ID 
name 
T2_ID

Let's say i need to select All tables names i would write a query:

select Table1.name, Table2.name, Table3.name 
from Table1
join Table2 on Table1.ID = Table2.T1_ID
join Table3 on Table2.ID = Table3.T2_ID

but how to select if i don't know the related columns now and i can only write 1 sql query. What i need to write instead of ???

select Table1.name, Table2.name, Table3.name 
from Table1
join Table2 on ???
join Table3 on ???
  • 1
    So, you don't know the columns, but the tables have foreign keys?, if so, the only way would be to construct your query with dynamic SQL. If the tables don't have foreign keysm then there's simple no way of doing this – Lamak Nov 20 '14 at 16:21
  • There is no way we can tell you what columns you should join on. If you have foreign keys you can look at the table definitions of sys.foreign_keys. – Sean Lange Nov 20 '14 at 16:21
  • use database diagram and 'view dependencies' – Dudi Konfino Nov 20 '14 at 16:51
  • Let's say system which i'm trying to make needs to be dynamic so system doesn't know **???** part and i want to write code which creates that part. @Lamak what do you mean by dynamic SQL? – Zigmantas Duoba Nov 20 '14 at 17:07
  • I can't explain what dynamic SQL is in a comment. Fortunately, you can google it and find a lot of good resources on that – Lamak Nov 20 '14 at 17:11
  • @Lamak So if my external database tables is related with foreign keys that means i can do it right? – Zigmantas Duoba Nov 20 '14 at 17:14

0 Answers0