views:

70

answers:

2

I have a stored procedure in SQL which I can't change. It needs few input parameters and returns a table with 100+ rows and several columns.

exec dbo.Select_Data 0, 0, 18, 50

I need something to get count of returned rows:

select count(*) from (exec dbo.Select_Data 0, 0, 18, 50)

and a way to get values from e.g. Name column:

select Id, Name from (exec dbo.Select_Data 0, 0, 18, 50) where Id=10

How do I do this?

+2  A: 

You need to create a temp table to hold the results of the stored procedure. you can then query the temp table. The schema of the temp table must match the output of the stored procedure.

Example:

CREATE TABLE #temp
(
ID INT,
NAME VARCHAR(100),
...
)

INSERT INTO #temp
Exec dbo.MyStoredProc

SELECT COUNT(*) FROM #temp

SELECT ID, NAME FROM #temp 
WHERE ID = 10

DROP TABLE #temp
Barry
I have a question regarding schema of output table. Do I need to write down the list all the parameters that stored procedure returns? Is there a way to avoid this step? What happens if someone updates that stored procedure without my knowing?
Krom
Checking `@@rowcount` instead of `SELECT COUNT(*) FROM #temp` should save a scan of the temp table.
Martin Smith
@Krom - The schema of the temp table must match the output from the Stored Procedure not the parameter list.
Barry
@MartinSmith - Good point
Barry
So you mean that it must match exactly and there's no way around it to query just the fields I need (Id, Name)? Cos I suspect that number of returned columns may depend on input parameters..
Krom
You can do but you need to consider some of the additional requirements: http://stackoverflow.com/questions/653714/how-to-select-into-temp-table-from-stored-procedure
Bronumski
@Bronumski - that is the exact question I was trying to find. Thanks
Barry
+1  A: 

You can insert the data into an in memory or temporary table (depending on the amount of data).

DECLARE @TempTable TABLE
(
     ID INT,
     DATA VARCHAR(20)
)
INSERT INTO @TempTable 
EXEC sp_executesql N'select 1 AS ID, ''Data'' AS DATA'

SELECT
*
FROM @TempTable 
Bronumski