views:

55

answers:

2

Hi,

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?

+1  A: 

Standard SQL can't do this. It's usually a bad design anyway. Certain vendors have extensions that allow this like Oracle has EXECUTE IMMEDIATE in anonymous PL/SQL blocks.

You either need to build up the statement externally or use something like a stored procedure to build up a statement and execute it.

cletus
I don't have any control over the database design. The database in question is the underlying Microsoft CRM database which seems pretty generic in all aspects. I can't identify any tables which provide the relationship instance information and as such I'm having to revert to finding the tables which should be joined in an alternative way.Maybe someone else knows how I can query an existing relationship in CRM from the database?
Brian Scott
+1  A: 

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:

declare @query nvarchar(max)
set @query = 'select * from t1 '

select  
    @query = @query + 'left join ' + name + 
        ' on t1.ActivityID = ' + name + '.ActivityID '
from sys.tables
where name like '%Activity%'

exec (@query)

Then again, I wonder how the calling program knows which fields to expect.

Andomar
Looks like you're thinking of the same dynamically combined SQL as I was initially thinking of. I'll go ahead using this route.
Brian Scott