Combine stored procedure and query in T-SQL

abatishchev picture abatishchev · Apr 1, 2010 · Viewed 36.6k times · Source

How do I combine executing of a stored procedure and using its result or parameters in a regular SQL query?

For example I would like to do something like the following:

-- passing result of SELECT to SP
SELECT a, b FROM t
EXEC my_sp a, b

-- passing result of SP to INSERT    
INSERT INTO t
EXEC my_sp a, b

etc.

Answer

KM. picture KM. · Apr 1, 2010

no, you need to use a temp table

create table #results (col1 int, col2 varchar(5) ...)

INSERT INTO #results
   EXEC YourProcedure @parma...

then you can join to it

SELECT
    *
    FROM YourTable     y
        JOIN #results  r ON ...
    ....

if you don't know the columns and data types from the procedure you can use this excellent answer: Insert results of a stored procedure into a temporary table

In brief it uses OPENROWSET to execute the stored procedure into a #temp table that is created on the fly, without the need to name and know the type all the columns.