简体   繁体   English

如何在SQL Server存储过程中使用变量作为服务器名称

[英]How to use variable for server name in SQL Server stored procedure

I have two database servers, server1 and server2 , which are our diff environment of our legacy system. 我有两个数据库服务器, server1server2 ,它们是我们遗留系统的差异环境。 I have to write a stored procedure for getting data which is communicate with one of the env. 我必须编写一个存储过程来获取与env之一进行通信的数据。

I want a way so that I can easily switch the env 我想要一种方法,以便我可以轻松切换env

Like: 喜欢:

Declare @Server nvarchar(20)
set @Server="server1"

select * 
from @Server.global.dbo.tblaccount

Parameters cannot be used for identifiers -- column names, table names, schema names, server names, function names, and so on. 参数不能用于标识符 - 列名,表名,模式名,服务器名,函数名等。

You can do this with dynamic SQL: 您可以使用动态SQL执行此操作:

declare @Server nvarchar(20);
declare @sql nvarchar(max);

set @Server = 'server1';

set @sql = 'select * from [Server].global.dbo.tblaccount';

set @sql = replace(@sql, '[Server]', @Server);

exec sp_executesql @sql;

use synonyms : 使用同义词

create synonym mylocalschema.RemoteTable for server1.database.schema.table;

to be referenced as: 被引用为:

select top 10 * from mylocalschema.RemoteTable;

depending on env the synonyms will be a reference to the right server and the code (sp, views, triggers, whatever) will be the very same for both. 取决于env,同义词将是对正确服务器的引用,并且代码(sp,views,triggers,等等)对于两者都是相同的。

the only duplicate item is the script to create synonyms: one for server1 and another copy for server2 (or maybe the same script built with dynamic sql...). 唯一重复的项是创建同义词的脚本:一个用于server1,另一个用于server2(或者可能是用动态sql构建的相同脚本...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM