无法从存储过程中的链接数据库返回值

时间:2017-08-01 08:48:18

标签: sql-server tsql openquery

我正在尝试编写一个存储过程(或函数,如果更容易)来查询链接数据库并返回一个值,但是大量挣扎。任何帮助都非常感谢...

我尝试过:

CREATE Proc dbo.Sample (@FolderID as VARCHAR(50),
@FolderName varchar(50) OUTPUT)
AS
BEGIN

DECLARE @ParamaterDefinition NVARCHAR(500)
DECLARE @FolderNameRet VARCHAR(50)
DECLARE @TSQL NVARCHAR(4000)

SET @TSQL = N'SELECT folder_name FROM OPENQUERY(LINKDB, ''SELECT 
        folder_name 
    FROM FolderTable
    where folder_id = '+ @FolderID +' and folder_status != 0'')'
SET @ParamaterDefinition = N'@FolderID as VARCHAR(50),
                    @FolderName VARCHAR(50) OUTPUT'
EXEC SP_EXECUTE @TSQL,
@ParamaterDefinition,
@FolderID,
@FolderName = @FolderNameRet output

SELECT @FolderNameRet AS "Output"
SELECT @FolderID AS "FolderID1"
SELECT @TSQL AS "Script"
SELECT @FolderName AS "FolderName1"
SELECT @ParamaterDefinition AS "Parameters"

RETURN @FolderNameRet 
END

使用末尾的SELECT语句查看每个变量,生成的脚本很好,可以单独运行它以获得我想要的值。但是@FolderNameRet仍然是NULL。

我觉得问题是我试图错误地返回一个值,但我尝试过的每个方法都失败了。

即。不要以为我可以在动态脚本中设置返回值,因为它需要以字符串格式作为OPENQUERY语句的一部分运行。也尝试使用EXEC @FolderNameRet = SP_EXECUTE @TSQL,但这也返回NULL。

请帮忙!

1 个答案:

答案 0 :(得分:1)

您可以尝试为@FolderName变量赋值:

SET @TSQL = N'SELECT @FolderName = folder_name FROM OPENQUERY(LINKDB, ''SELECT 
        folder_name 
    FROM FolderTable
    where folder_id = '+ @FolderID +' and folder_status != 0'')'
SET @ParamaterDefinition = N'@FolderID as VARCHAR(50),
                    @FolderName VARCHAR(50) OUTPUT';

存储过程RETURN的状态为INT而不是VARCHAR(50)