sql query from usp results
-
05-07-2019 - |
Question
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''."
Solution
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 ...
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow