3

I tried to create an stored procedure in a remote server using this way

EXECUTE (N'USE [master]; EXEC sp_executesql N'+ @sqlCommand) AT [LinkedServer]

However I received this error

Msg 111, Level 15, State 1, Procedure StoredProcedure, Line 5 [Batch Start Line 0] 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

in the sqlCommand has the query similar this

SET @sqlCommand = '
CREATE OR ALTER PROCEDURE [dbo].[storedName]
    @nameDB varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQLProcessesRep varchar(max);

    --Actions in Stored
END'

2 Answers 2

5

You can call sp_executesql directly in the context of the linked server's master database, using four-part naming.

EXEC LinkedServer.master.sys.sp_executesql @sqlCommand;

If the linked server name is in a variable you can even do this dynamically

DECLARE @proc nvarchar(1000) = @dbname + N'.master.sys.sp_executesql';
EXEC @proc @sqlCommand;
1
  • Thanks a lot this option EXEC LinkedServer.master.sys.sp_executesql @sqlCommand; works. Commented May 30 at 3:13
2

well yeah

You have two options:

  1. Remove the USE [master]; before the EXEC, and rely on the user's default database being master
  2. Execute sys.sp_executesql in the context of the master database

Your second option would look like this:

EXECUTE (N'EXEC master.sys.sp_executesql N'+ @sqlCommand) AT [LinkedServer];

If you hit any additional issues, please ask a new question.

1
  • Thanks a lot, is a great solution, regards. Commented May 30 at 3:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.