简体   繁体   中英

Stored procedure to Linked server with parameters - Error

I'm trying to create stored procedure to Linked server , which input parameter @ServerName is the name of Linked Server i use. In this procedure I also Declare parameter which value I want to get from Dynamic SQL Query and line.

CREATE PROC sp_Version @ServerName varchar(30)
as
Declare @Ver varchar(10)
exec ('select @Ver from openquery(' + @ServerName + ', ''SELECT SUBSTRING (@@VERSION, 22, 7) = @Ver''')

When I execute my sp i get an error saying:

"Must declare the scalar variable "@Ver"."

Could you please help me?

I'm not sure what your aim is with the value of @Ver, perhaps an OUTPUT parameter? If so, then the syntax would be:

CREATE PROC GetVersion @ServerName varchar(30), @Ver nvarchar(500) OUTPUT AS

    DECLARE @SQL nvarchar(MAX);

    SET @SQL = N'SELECT @dVer = Version' + NCHAR(10) +
               N'FROM OPENROWSET(''SQLNCLI'',' + NCHAR(10) +
               N'                ' + QUOTENAME('Server=' + @ServerName + ';Trusted_Connection=YES;','''') + ',' +NCHAR(10) +
               N'                ''SELECT @@VERSION AS Version'');';

    PRINT @SQL;
    EXEC sp_executesql @SQL, N'@dVer nvarchar(500) OUTPUT', @dVer = @Ver OUTPUT;


GO

DECLARE @ver varchar(500)

EXEC GetVersion 'YourServerName', @ver OUTPUT;

PRINT @ver;
GO

DROP PROC GetVersion;

Note, firstly, as suggested I didn't use the sp_ prefix. I've also used sp_executesql instead of simply EXEC (this is generally better practice, as you can parametrise your dynamic SQL then, as i have done), and QUOTENAME to try and avoid injection.

I have come across this situation a couple of times. Try this:

CREATE PROC sp_Version @ServerName varchar(30)
as
Declare @Ver varchar(10)

DECLARE @SqlCommand nvarchar(MAX)

SET @SqlCommand = 'SELECT @Ver2 = SUBSTRING (@@VERSION, 22, 7) '

DECLARE @sp_executesql VARCHAR(100)
SET @sp_executesql = @ServerName + '.master.sys.sp_executesql'
EXEC @sp_executesql @SqlCommand, N'@Ver2 nvarchar(10) out', @Ver out
SELECT @Ver

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