I have a stored procedure that returns 80 columns, and 300 rows. I want to write a select that gets 2 of those columns. Something like
SELECT col1, col2 FROM EXEC MyStoredProc 'param1', 'param2'
When I used the above syntax I get the error:
"Invalid Column Name".
I know the easiest solution would be to change the stored procedure, but I didn't write it, and I can't change it.
Is there any way to do what I want?
I could make a temp table to put the results in, but because there are 80 columns so I would need to make an 80 column temp table just to get 2 columns. I wanted to avoid tracking down all the columns that are returned.
I tried using
WITH SprocResults AS ....
as suggested by Mark, but I got 2 errorsIncorrect syntax near the keyword 'EXEC'.
Incorrect syntax near ')'.I tried declaring a table variable and I got the following error
Insert Error: Column name or number of supplied values does not match table definition
If I try
SELECT * FROM EXEC MyStoredProc 'param1', 'param2'
I get the error :Incorrect syntax near the keyword 'exec'.
A quick hack would be to add a new parameter
'@Column_Name'
and have the calling function define the column name to be retrieved. In the return part of your sproc, you would have if/else statements and return only the specified column, or if empty - return all.Source:
http://stevesmithblog.com/blog/select-from-a-stored-procedure/
As it's been mentioned in the question, it's hard to define the 80 column temp table before executing the stored procedure.
So the other way around this is to populate the table based on the stored procedure result set.
If you are getting any error, you need to enable ad hoc distributed queries by executing following query.
To execute
sp_configure
with both parameters to change a configuration option or to run theRECONFIGURE
statement, you must be granted theALTER SETTINGS
server-level permissionNow you can select your specific columns from the generated table