简体   繁体   中英

Run stored procedure on linked server (linked server name as variable)

I have a script and its works well:

DECLARE @RunSPSQL VARCHAR(60);

SET @RunSPSQL = 'EXEC master.dbo.sp_test';

EXEC (@RunSPSQL) AT LNK_SERVER_NAME;

Now I would like to change linked server name to variable, something like this:

DECLARE @RunSPSQL VARCHAR(60);
DECLARE @LNK_Name NVARCHAR(60);

SET @RunSPSQL = 'EXEC master.dbo.sp_test';
SET @LNK_Name = 'LNK_SERVER_NAME';

EXEC (@RunSPSQL) AT @LNK_Name;

But it doesn't work:

Incorrect syntax near '@LNK_Name'

I was looking for a solution, but no success for now.

If anyone, please help.

You can't use a variable to replace the name of an object. Instead you need to use some dynamic SQL to achieve this:

DECLARE @RunSPSQL varchar(60);
DECLARE @LNK_Name nvarchar(60);
DECLARE @SQL nvarchar(MAX);
SET @RunSPSQL = 'EXEC master.dbo.sp_test';
SET @LNK_Name = N'LNK_SERVER_NAME';

SET @SQL = N'EXEC (@RunSPSQL) AT ' + QUOTENAME(@LNK_Name) + N';';
EXEC sp_executesql @SQL, N'@RunSPSQL varchar(60)', @RunSPSQL = @RunSPSQL;

Just ensure you quote the linked server's name to avoid any injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM