0

I have several link server on my server (about 20 servers). on these server exists a similar database and I want to execute a stored procedure on these server in depend of a parameter on my stored procedure on my server. I have following query for this idea.

Create procedure test
    (
       @ServerName VarChar(100),
       @Code int
    )
As
    IF(@ServerName = 'Server1')Begin
       Exec Server1.SGDB.dbo.DocInsert @Code
    End Else IF(@ServerName = 'Server2')Begin
       Exec Server2.SGDB.dbo.DocInsert @Code
    End Else IF(@ServerName = 'Server3')Begin
       Exec Server3.SGDB.dbo.DocInsert @Code
    .
    .
    .
    End Else IF(@ServerName = 'Server20')Begin
       Exec Server20.SGDB.dbo.DocInsert @Code
    End
End

Can I have a dynamic query with @ServerName parameter without using exec(string command).

thanks in advance.

1 Answer 1

1

You can replace the body of your stored procedure with this dynamic SQL:

declare @sql nvarchar(max)

set @sql = N'Exec ' + @ServerName + N'.SGDB.dbo.DocInsert @Code'

exec sp_executesql  @stmt = @sql, @params = N'@Code int', @Code = @Code

It will be also better to declare the parameter @ServerName as NVarChar(128) to always work on Unicode characters and to allow for the maximum length of a linked server name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.