Saturday, February 25, 2012

Capturing the output from store procedure and use it

How do I call capture the output (not return value) from calling a store procedure from within a store procedure so I can use that data for further processing (say join it with another table)?

For example,

CREATE PROCEDURE dbo.sp_test AS
-- returns all words not in Mastery Level 0

EXEC sp_anothertest

-- use the data coming back from sp_test and join it with another table here and say insert them into tblFinalResults

SELECT * tblFinalResults
GO

Thanks!I do not think you can do this exactly as you would like. You may need to resort to either a UDF which returns a table, using table variables within the stored procedure, or using temporary tables. Functions are the most flexiable and temporary tables are the slowest. You can also use table variables as output parameters of the stored procedures. Below is an example of using table variables.
begin
DECLARE @.Result1 table (key1 int, foo varchar(32) )
insert into @.Result1 select 1, 'This is Table 1'

DECLARE @.Result2 table ( key2 int, foo varchar(32) )
insert into @.Result2 select 1, 'This is Table 2'

select * from @.Result1 inner join @.Result2 on( key1 = key2 )
end

No comments:

Post a Comment