HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Dynamic database reference in T-SQL scripts

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
referencescriptssqldatabasedynamic

Problem

We have a set of databases (development, QA and production, dev-foo & dev-bar, qa-foo & qa-bar and just foo & 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 .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 ` that would point to an appropriate "instance" of a bar` database?

Solution

The answer is Synonyms.

Repeat for each database in foo family:

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


And then use it as follows:

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

Code Snippets

create synonym bar for [srv-db].<bar-db>.dbo.bar;
select f.*, b.* 
from foo f inner join bar b on f.barid = b.id ;

Context

StackExchange Database Administrators Q#29051, answer score: 9

Revisions (0)

No revisions yet.