Inserting Results from a Stored Procedure Call to a Table
This is handy, bumped into this and I thought it would be nice to take note and share.
What this code illustrate is that you can basically use a stored procedure's result and insert it into a table and do your own query.
Now why do we want to do that? Say for example the existing query does something and is being used by different modules and touching it would require us to check/test those modules that has a dependency on the SP.
Applying the sample below allows us to just reuse the existing SP and get the resulting data and do our own filters, grouping etc..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | DECLARE @Table TABLE( SPID INT, Status VARCHAR(MAX), LOGIN VARCHAR(MAX), HostName VARCHAR(MAX), BlkBy VARCHAR(MAX), DBName VARCHAR(MAX), Command VARCHAR(MAX), CPUTime INT, DiskIO INT, LastBatch VARCHAR(MAX), ProgramName VARCHAR(MAX), SPID_1 INT, REQUESTID INT ) INSERT INTO @Table EXEC sp_who2 SELECT * FROM @Table WHERE .... |
The code above shows a built-in stored procedure sp_who2 being called and inserted to a table variable and was selected. sp_who2 BTW, shows all the sessions that are currently established in the database, this sp is normally used to diagnose system slow down.
Comments