将服务器名称作为变量

时间:2009-04-17 10:24:49

标签: sql sql-server tsql

我正在尝试从不同的服务器获取数据,并且服务器名称可能会更改。所以我将服务器名称设置为参数。我的sql存储过程的想法是这样的

CREATE PROCEDURE [dbo].[GetData]
        @ServerName
AS
BEGIN
    SELECT * FROM @ServerName.ClientDataBase.dbo.Client
END

有谁知道如何实现这一目标?

数据库版本是sql server 2005

4 个答案:

答案 0 :(得分:5)

使用动态SQL,但这可能是邪恶的:

exec('select * from ' + @ServerName + '.ClientDatabase.dbo.Client')

答案 1 :(得分:3)

看看使用同义词

创建语法(来自MSDN):

CREATE SYNONYM [ schema_name_1. ] synonym_name FOR < object >

< object > :: =
{
    [ server_name.[ database_name ] . [ schema_name_2 ].| 
         database_name . [ schema_name_2 ].| schema_name_2. ] object_name
}

答案 2 :(得分:3)

您可以设置链接服务器,“BOB”。

然后,您可以调用sp_setnetname来更改基础目标服务器,但保留名称BOB。

所以你的代码是:

CREATE PROCEDURE [dbo].[GetData]
        @ServerName
AS
BEGIN
    EXEC sp_setnetname 'BOB', @ServerName
    SELECT * FROM BOB.ClientDataBase.dbo.Client
END

答案 3 :(得分:0)

-- Proc to get remove server name (domaine+instance name)

IF OBJECT_ID('dbo.getRemoteName') IS NOT NULL
        DROP PROC dbo.getRemoteName;
GO
CREATE PROC dbo.getRemoteName
 @id AS INT,
 @RETURN AS VARCHAR(100) OUTPUT
AS 
BEGIN 
 DECLARE @GetInstances TABLE
 ( id INT IDENTITY(0,1),
  VALUE NVARCHAR(100),
   instanceName NVARCHAR(100),
  DATA NVARCHAR(100))

 INSERT INTO @GetInstances
 EXECUTE xp_regread
 @rootkey = 'HKEY_LOCAL_MACHINE',
 @KEY = 'SOFTWAREMicrosoftMicrosoft SQL Server',
 @value_name = 'InstalledInstances'

 -- order ascendant 
 -- Select * from @GetInstances -- uncomment to see all the instances that your have
 SELECT @RETURN=instanceName FROM @GetInstances WHERE id=@id ORDER BY instanceName ASC;
 SET @RETURN=HOST_NAME()+''+@RETURN;
END;
GO

DECLARE @RETURN AS VARCHAR(100);
-- get the instance number 0
EXEC getRemoteName 0, @RETURN OUTPUT;
PRINT @RETURN; 





-- 

exec('SELECT * FROM ['+@RETURN+'].RemoteDatabase.dbo.SampleTable');