How to execute another stored procedure in a stored procedure and get the result set it returns

Source: Internet
Author: User

Background

In the process of writing SQL Server stored procedures, there are often complex business logic, it is common practice to split a large stored procedure into several small stored procedures.

Problem

You need to call stored procedure b in stored procedure A, and stored procedure B returns a table,a that needs to be fetched to table B, and then the next step is processed.

The problem solved in this article is: How to execute B in a and get the return table of B

Ideas

Use exec in a to execute stored procedure b

Define a temporary table in a and insert the data returned by B into a temporary table

Steps

Create a new test table and insert some data into the table in bulk

CREATE TABLE testtable (ID INT)
    
INSERT into  testtable
        select  1
        Union
        Select  2
        Union
        Select  3
            
select * FROM TestTable

New stored procedure b,b returns a table

CREATE PROCEDURE [dbo]. [Up_b]
as BEGIN
      SELECT ID, ' Comefromb ' from testtable       
end

The new stored procedure A,a call B and inserts the table returned by B into the temporary table defined by a

CREATE PROCEDURE [dbo]. [Up_a]
As
BEGIN
      CREATE TABLE #Temp (ID int,msg VARCHAR ())
      INSERT into #Temp EXEC up_b
          
      SELECT * from #Temp   
E ND

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/database/SQLServer/

Execution results

All code

CREATE TABLE testtable (ID INT)
    
INSERT into  testtable
        select  1
        UNION
        Select  2
        UNION
        SELECT  3
go
    
CREATE PROCEDURE [dbo].[ Up_b]
as BEGIN
      SELECT ID, ' Comefromb ' from TestTable end go
    
CREATE PROCEDURE [dbo].[ UP_A]
as
BEGIN
      CREATE TABLE #Temp (ID int,msg VARCHAR ())
      INSERT into #Temp EXEC up_b
          
      SELECT * From #Temp   
to
    
EXEC [up_a]
Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.