我们有一组数据库(开发、QA 和生产,分别是dev-foo
& dev-bar
、qa-foo
&qa-bar
和 just foo
& bar
)。
在foo
数据库系列中,有一个视图应该使用各自的bar
数据库进行跨数据库连接。换句话说,
select f.*, b.* from foo f inner join <bar-db>.dbo.bar b on f.barid = b.id
Run Code Online (Sandbox Code Playgroud)
问题是:有什么办法可以让我编写一次这个脚本,然后有一个数据库级变量<bar-db>
指向一个适当的bar
数据库“实例” ?
答案是同义词。
对系列中的每个数据库重复foo
:
create synonym bar for [srv-db].<bar-db>.dbo.bar;
Run Code Online (Sandbox Code Playgroud)
然后按如下方式使用它:
select f.*, b.*
from foo f inner join bar b on f.barid = b.id ;
Run Code Online (Sandbox Code Playgroud)