views:

549

answers:

7

Say I have a stored procedure that returns rows:

CREATE PROCEDURE MyProc
AS
BEGIN
    SELECT * FROM MyTable
END

Of course my actual procedure is a little more complicated, being why a sproc is necessary.

Is it possible to select the output from calling this procedure?

Something like:

SELECT * FROM (EXEC MyProc) AS TEMP

The reason, is I need to use SELECT TOP X, ROW_NUMBER, and an additional WHERE clause to page my data, and I don't really want to pass these values as parameters.

+7  A: 

You either want a Table-Valued function or insert your EXEC into a temporary table:

INSERT INTO #tab EXEC MyProc
CMerat
A: 

You can

  1. create a table variable to hold the result set from the stored proc and then
  2. insert the output of the stored proc into the table variable, and then
  3. use the table variable exactly as you would any other table...

    Declare @T Table ([column definitions here])

    Insert @T Exec storedProcname params

    Select * from @T Where ...

Charles Bretana
+1  A: 

It sounds like you might just need to use a view. A view allows a query to be represented as a table so it, the view, can be queried.

Lawrence Barsanti
+1  A: 

You can copy output from sp to temporaty table.

CREATE TABLE #GetVersionValues
(
    [Index] int,
    [Name] sysname,
    Internal_value int,
    Character_Value sysname
)
INSERT #GetVersionValues EXEC master.dbo.xp_msver 'WindowsVersion'
SELECT * FROM #GetVersionValues
drop TABLE #GetVersionValues
+7  A: 

You can use a User-defined function or a view instead of a procedure.

A procedure can return multiple result sets, each with its own schema. It's not suitable for using in a SELECT statement.

Mehrdad Afshari
Additionally, if after converting to a UDF you find you need the stored procedure semantics you can always wrap the UDF with a procedure.
Joel Coehoorn
+5  A: 

You should look at this excellent article by Erland Sommarskog:

It basically lists all available options for your scenario.

kristof
+1, there are more ways than you might think
KM
This should really be the accepted answer. The article referenced is very thorough.
ssmith
A: 

You can cheat a little with OPENROWSET :

SELECT ...fieldlist... FROM OPENROWSET('SQLNCLI', 'connection string', 'name of sp') WHERE ...

This would still run the entire SP every time, of course.

CodeByMoonlight