Ask the Expert

How to use results from one stored procedure in another

I've written a stored procedure for use in a Crystal Report. It works great. I would also like to use the results from this stored procedure in another stored procedure. How do I do this?

    Requires Free Membership to View

So long as the stored procedure produces only a single result, the technique for using the output of one stored procedure in another is pretty straightforward. The technique is to use a temporary table to hold the results of the stored procedure and an INSERT EXEC statement to execute the sproc and save the results. Once the results are in the temporary table they can be used like any other table data.

Here's an example procedure that we might like to reuse:

CREATE PROC  usp_Demo_AllAuthors as

    select * from pubs..authors

Now here's a stored procedure that uses the results of usp_Demo_AllAuthors:

CREATE proc usp_Demo_SPUser as 

    CREATE TABLE #Authors (
     au_id varchar(11) NOT NULL PRIMARY KEY CLUSTERED,
     au_lname varchar (40) NOT NULL ,
     au_fname varchar (20) NOT NULL ,
     phone char (12) NOT NULL,
     address varchar (40) NULL ,
     city varchar (20) NULL ,
     state char (2) NULL ,
     zip char (5) NULL ,
     contract bit NOT NULL
    -- Execute usp_Demo_AllAuthors storing the
    -- results in #Authors
    insert into #Authors
     exec usp_Demo_AllAuthors
    -- Here we use the #Authors table.  This example only
    -- only selects from the temp table but you could do much
    -- more such as use a cursor on the table or join with 
    -- other data.
    SELECT au_fName + ' ' + au_lname as [name]
         , address+', '+city+', '+state+' '+zip [Addr] 
        from #Authors
    DROP TABLE #Authors

Do you have comments on this Ask the Expert Q&A? Let us know.

This was first published in May 2005

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: