Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the results of a stored procedure from within another?

I have a stored procedure that I want to call from within another, and then loop through the results. Sort of like using a cursor with a stored procedure rather than a SQL select statement. I can't quite figure out how to do it.

I can get the whole result like this:

DECLARE @result int;
EXEC @result = sp_who;
PRINT @result;

Interestingly, this seems to change the type of @result to something other than int, but whatever. How do I then loop through the results, row by row? How do access the data from the individual columns? For example, how would I kill processes where the forth column (loginname) is like '%gatesb' or whatever?

like image 950
TallGuy Avatar asked May 14 '09 01:05

TallGuy


People also ask

How do you use a stored procedure in another stored procedure?

Here is an example of how to call a stored procedure inside another stored procedure. This is also known as nested stored procedures in SQL Server. Step 1: Create two simple stored procedure to insert some data into two different tables. both accept four parameters to insert the data.

Can I call a stored procedure from another?

In releases earlier than SQL Server 2000, you can call one stored procedure from another and return a set of records by creating a temporary table into which the called stored procedure (B) can insert its results or by exploring the use of CURSOR variables.


2 Answers

Rewrite sp_who as a table function

like image 117
Linda Avatar answered Oct 17 '22 07:10

Linda


You would declare a table variable to hold the results of the stored procedure and then loop through them in a while loop:

declare @temp table (
    idx int identity(1,1),
    field1 int,
    field2 varchar(max))

declare @result int

insert into @temp (field1, field2)
exec @result = sp_who

declare @counter int

set @counter = 1

while @counter < (select max(idx) from @temp)
begin
    -- do what you want with the rows here
    set @counter = @counter + 1
end
like image 36
Justin Niessner Avatar answered Oct 17 '22 09:10

Justin Niessner