Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make server name as a variable

I am trying to get data from different sever, and the sever name might change. So I set the server name as a parameter. The idea of my sql store procedure is something like this

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

Does anyone know how to achieve this?

The database version is sql server 2005

like image 299
wschenkai Avatar asked Apr 17 '09 10:04

wschenkai


2 Answers

Use dynamic SQL, however evil this may be:

exec('select * from ' + @ServerName + '.ClientDatabase.dbo.Client')
like image 64
Anton Gogolev Avatar answered Sep 21 '22 23:09

Anton Gogolev


Look at using Synonym(s)

Create syntax (from 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
}
like image 42
cjk Avatar answered Sep 19 '22 23:09

cjk