Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine stored procedure and query in T-SQL

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.

like image 672
abatishchev Avatar asked Apr 01 '10 19:04

abatishchev


People also ask

How do I combine two stored procedures at the same time?

Use the sql server "Generate Script" Wizard. Click Next on the "Introduction" window and in the 2nd screen select the option button "Specific Database objects" and click the combo box near "Stored Procedure" (If you are only taking the scripts of stored procedures.


1 Answers

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.

like image 147
KM. Avatar answered Sep 21 '22 11:09

KM.