TSQL: Call a stored procedure from another stored procedure and read the result

后端 未结 5 1639
自闭症患者
自闭症患者 2020-12-14 15:29

I have a stored procedure that, ending with a SELECT, returns a recordset. I can call it within anoher stored procedure like this:

EXEC procedure @param


        
相关标签:
5条回答
  • 2020-12-14 15:59

    You can create a temp table and then use INSERT INTO #MyTable EXEC procedure @param.

    There are some other techniques listed here.

    0 讨论(0)
  • 2020-12-14 16:03

    AFAIK, you can't. What you probably want to do is use a function for your first (or both) procedures. Functions can only return one thing, but they can return a table. Stored procedures can return multiple results, but not to other functions/stored procedures.

    e.g.:

    CREATE FUNCTION [dbo].[fn_GetSubordinates] (
        @sPersonID VARCHAR(10),
        @nLevels INT
    )
    RETURNS @tblSubordinates TABLE
    (
        Person_Id VARCHAR(10),
        Surname char(25),
        Firstname char(25)
    )
    AS
    BEGIN
        ...
    
    0 讨论(0)
  • 2020-12-14 16:17

    First, you CANNOT RETURN a recordset by stored procedure. By return, a stored procedure can only return integers.

    You mentioned SELECT statement, which is a DQL and just for display purpose.

    The way you can do to work around this issue is that you can assign the recordset to a global temporary table which can also be accessed within the outer stored procedure.

    0 讨论(0)
  • 2020-12-14 16:18

    If you are using SQL Server 2008, I would recommend returning a Table-Valued Parameter.

    http://msdn.microsoft.com/en-us/library/bb510489.aspx

    0 讨论(0)
  • 2020-12-14 16:22

    You can do this with an output variable in the stored proc. For example:

    CREATE PROCEDURE sp_HelloWorld   @MyReturnValue int OUT
    AS
    SELECT @MyReturnValue = 100
    Return @MyReturnValue 
    

    To call this stored proc, do the following:

    DECLARE @TestReturnVal int 
    
    EXEC sp_HelloWorld @TestReturnVal output
    SELECT @TestReturnVal 
    
    0 讨论(0)
提交回复
热议问题