Dynamic database reference in T-SQL scripts We have a set of databases (development, QA and production, dev-foo &amp; dev-bar, qa-foo &amp; qa-bar and just foo &amp; bar respectively).

Inside foo family of databases there's a view that should use respective bar database to do cross-database joins. In other words,

select f.*, b.* from foo f inner join &lt;bar-db&gt;.dbo.bar b on f.barid = b.id


The question is: is there any way I could write this script once and then have a database-level variable &lt;bar-db&gt; that would point to an appropriate "instance" of a bar database?
The answer is Synonyms.

Repeat for each database in foo family:

create synonym bar for [srv-db].&lt;bar-db&gt;.dbo.bar;


And then use it as follows:

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