I’m looking for a way to join a series of SQL tables based on a list of table names. The list of table names can change as the system grows but I need to make sure the join operates on all the tables as they grow.
Each table in the list will have a common column called ActivityID which is a foreign key back to the Activity table which is the source table of the join.
I’d thought about maybe creating a varchar and building the query up before executing. Is this the best way or can the join syntax be created without varchar building?
I’d place the query in a view. When you add a new table, alter the view to include the new table. That would be much more efficient than dynamic sql.
If you don’t control who/when adds a table, something like the following dynamic SQL would work in Sql Server:
Then again, I wonder how the calling program knows which fields to expect.