代码之家  ›  专栏  ›  技术社区  ›  Tim Rose

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

  •  2
  • Tim Rose  · 技术社区  · 7 年前

    我所尝试的:

    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仍然是空的。

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

    请帮忙!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Lukasz Szozda    7 年前

    您可以尝试为@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) .