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'
asked May 29, 2024 at 23:07

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;
answered May 30, 2024 at 0:39
1
  • Thanks a lot this option EXEC LinkedServer.master.sys.sp_executesql @sqlCommand; works. Commented May 30, 2024 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.

answered May 29, 2024 at 23:28
1
  • Thanks a lot, is a great solution, regards. Commented May 30, 2024 at 3:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.