开发者

Which are the problems in creating and dropping a linked server just for executing a remote query?

开发者 https://www.devze.com 2023-01-15 16:21 出处:网络
I need to retrieve some data from a remote database, it is a kind of \"updates manager\", so my application will connect to that remote server to check if there are new updates.

I need to retrieve some data from a remote database, it is a kind of "updates manager", so my application will connect to that remote server to check if there are new updates.

I use a webserver for doing the "handshake and validation" work, but then I connect directly to a remote sql server to retrieve the data.

The webserver will return the login info (serverIP+Port, database, user and password), of course the user is a user with datareader (on a subset of the tables) rights only.

What I need to do is execute some remote queries for retrieveing the needed data. This is what i wrote (and it works):

CREATE PROCEDURE QueryRemoteServer 
      (@SERVER nvarchar(50),@FieldNames nvarchar(500), @DB nvarchar(50),
       @Tablename nvarchar(100), @Login Nvarchar(50),@pwd Nvarchar(50))
AS
BEGIN
  /* Creation of Linked Server including the If exists check */
  if exists (Select name From sys.servers Where [Name]=@SERVER) 
  exec sp_dropserver @SERVER, 'droplogins' 
  exec sp_addlinkedserver @SERVER
  /* Creation of the login according to values returned from webserver */
  exec sp_addlinkedsrvlogin @SERVER, 'FALSE', NULL, @Login, @pwd
  /* exec the query (for simplicity I omitted the JOIN job) */
  exec ('SELECT ' +  @FieldNames + 
          ' FROM ['+ @Server + '].' + @Db + '.dbo.' + @Tablename)
  /* drop the created linked server */ 
  exec sp_dropserver @SERVER, 'droplogins' 
END

The client will simply run something like this:

exec QueryRemoteServer '127.0.0.1 , 4455','Field1, Field2',
           'MyR开发者_高级运维emoteDB','MyRemoteTable','GuestUser','GuestPassword'

Could you please tell me your opionions about this approach and tell me which are the major faults/benefits you see?


Have you considered using OPENROWSET instead of creating/dropping the linked server every time?

0

精彩评论

暂无评论...
验证码 换一张
取 消