Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-Sql How to return a table from a storedproc in another stored proc

I would like to do the following. Basically have a stored procedure call another stored procedure that returns a table. How is this done?

    ALTER PROC [GETSomeStuff]
    AS
    BEGIN

    @table = exec CB_GetLedgerView @accountId, @fromDate, @toDate, @pageSize, @pageNumber, @filter, @status, @sortExpression, @sortOrder, @virtualCount OUTPUT

   Select * from @table
   --Do some other stuff here        
    END
like image 864
Arron S Avatar asked Feb 02 '09 19:02

Arron S


People also ask

Can we return table from stored procedure in SQL?

The RETURN exits the stored procedure, and nothing that follows it will be executed, including the SELECT statement on the following line. Otherwise, if you want the data for the entire table, as your question shows, add a SELECT after the INSERT . But don't put RETURN in front of it!

Can we access a temp table of one stored procedure from another stored procedure?

The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table."

How do you pass a table variable from one stored procedure to another?

You will need to create a TABLE TYPE then Declare a parameter of that type and yes it will be a read-only param but then you can get data into another table variable or temp table inside your param and do whatever you want to do with it.


2 Answers

The target of a stored procedure has to be a temp or actual table so you can

    Insert into #table exec CB_GetLedgerView @accountId, @fromDate, 
@toDate, @pageSize, @pageNumber, 
@filter, @status, @sortExpression, 
@sortOrder, @virtualCount OUTPUT

If the output result set of the stored procedure does not match the ordinal positions and count of the rows in the target table, specify a column list.

like image 158
cmsjr Avatar answered Sep 22 '22 13:09

cmsjr


The temporary-table approach, at least as expressed above, didn't work for me. You can use a variable, just as easily.

DECLARE @return_value INT
DECLARE @tblOutputTable TABLE(Col1 BIT NOT NULL, Col2 INT NOT NULL)

INSERT INTO @tblOutputTable EXEC @return_value = [dbo].[SomeSp] @Param1 = 15, @Param2 = 2
like image 26
Dustin Oprea Avatar answered Sep 23 '22 13:09

Dustin Oprea