views:

200

answers:

2

How to query the results of a stored procedure?

Here's my example:

sp_columsn 'tblSomeTableName' --// Returns a recordset

select COLUMN_NAME from [sp_columns 'tblSomeTableName'] --// Raises an error saying "Invalid object name 'sp_columns 'tblSomeTableName''."
+2  A: 

as long as you know the structure of the results of the stored proc, you can create a table (temp, variable, etc) and execute the stored proc into the table.

CREATE TABLE #MyTestTable
(TABLE_QUALIFIER sysname, 
TABLE_OWNER sysname, 
TABLE_NAME sysname, 
COLUMN_NAME sysname, 
DATA_TYPE smallint, 
TYPE_NAME sysname, 
PRECISION int, 
LENGTH int, 
SCALE smallint, 
RADIX smallint, 
NULLABLE smallint, 
REMARKS varchar(254), 
COLUMN_DEF nvarchar(4000), 
SQL_DATA_TYPE smallint, 
SQL_DATETIME_SUB smallint, 
CHAR_OCTET_LENGTH int, 
ORDINAL_POSITION int, 
IS_NULLABLE varchar(254), 
SS_DATA_TYPE tinyint)

INSERT  #MyTempTable
EXEC    sp_columns 'tblSomeTableName'

SELECT  COLUMN_NAME
FROM    #MyTempTable
WHERE   ...
Scott Ivey
This is the correct method. Unfortunately, there isn't any "direct" way to do it without the temp table.
BradC
There is by doing a loopback query
SQLMenace
+1  A: 

you could do a loopback query but be advised that it opens another connection to the same server

SELECT *
      FROM OPENROWSET ('SQLOLEDB','Server=(local);TRUSTED_CONNECTION=YES;',
    'set fmtonly off exec master.dbo.sp_who')

See also here: Store The Output Of A Stored Procedure In A Table Without Creating A Table

SQLMenace
Nice trick, but makes me cringe. It just feels like a hack, but I can see so many places where it would be usefull...
Dems