views:

31

answers:

2

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',
           'MyRemoteDB','MyRemoteTable','GuestUser','GuestPassword'

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

+2  A: 

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

Joe Stefanelli
Yes, you mean for select statements it would be a better approach? Less problems since no need to create and destroy linked servers?
You are correct.
Joe Stefanelli
Ok thanks, until I just need to execute select statements it is a better idea.
+1  A: 

One problem I would see is that no dba in his or her right mind would give a user the right to create and drop linked servers!

HLGEM
In my case this is not a problem since I am always dba. In the general case of course you are more than right.