Dynamic database reference in T-SQL scripts
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 ;