Dynamic database reference in T-SQL scripts

The answer is Synonyms.

Repeat for each database in foo family:

create synonym bar for [srv-db].<bar-db>.dbo.bar;

And then use it as follows:

select f.*, b.* 
from foo f inner join bar b on f.barid = b.id ;

Synonyms and dynamic SQL are both solid answers (although you can't use dynamic SQL within a view). If you are using Visual Studio to manage your database projects, there is another route open to you: database variables. If you have database projects named foo and bar and configurations Debug, QA, and Release, you could use an app.config transform (perhaps using a tool like Slow Cheetah) and on deployment, the correct database reference would be used and a later DBA wouldn't get confused as to what "foo" means in that context. Synonyms aren't very commonly used in my experience, so they are something that one could easily overlook.

Tags:

T Sql