Passing linkserver name as a varible to openquery

Last post 02-25-2008, 11:45 PM by subodhk. 2 replies.
Sort Posts: Previous Next
  •  02-25-2008, 8:19 AM Post number 44443

    Passing linkserver name as a varible to openquery

    Hi,
           I have to pass a variable as a Linked server name to the openquery to make my storedprocedure genric so that if the linked server changes than I dont have to change the stored procedure.
    Is there any way to do this or any workaround?

    Example
    Declare @ServerName varchar(50)
    Select * from OPENQUERY(@ServerName,'Select * from master.dbo.spt_values')

    This problem has bogged me for a long time. Need help urgently.

    Thank You
  •  02-25-2008, 3:57 PM Post number 44464 in reply to post number 44443

    Re: Passing linkserver name as a varible to openquery

    I guess there are many ways to do this but here is one suggested by Microsoft:

     

    DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000)
    SET @LinkedServer = 'MyLinkedServer'
    SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ','''
    SET @TSQL = 'SELECT au_lname, au_id FROM pubs..authors'')'
    EXEC (@OPENQUERY+@TSQL)

  •  02-25-2008, 11:45 PM Post number 44497 in reply to post number 44464

    Re: Passing linkserver name as a varible to openquery

    Hi Calvino,
         Thanks for the reply. I have seen this post but I dont need any Exec to execute it.
    I need the the select statement to work with openquery as I have to use the resultset to perform other task.
View as RSS news feed in XML