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

后端 未结 4 394
有刺的猬
有刺的猬 2020-12-19 00:54

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 s

相关标签:
4条回答
  • 2020-12-19 01:01

    What Justin pointed out is what you have to do, but instead of doing

    while @counter < (select max(idx) from @temp)
    

    do this

    declare @maxid int
    select @maxid = max(idx), @counter = 1
    from @temp
    while @counter < @maxid begin
    -- go on
      set @counter = @counter + 1
    end
    

    Also, if declaring the table as @temp doesn't work you could declare it as #temp.

    0 讨论(0)
  • 2020-12-19 01:02

    you can catch the results of a stored proc by inserting into a table that has matching columns...

    create table #spWhoResults
        (spid smallint,
        ecid smallint,
        status nchar(60),
        loginame nchar(256),
        hostname nchar(256),
        blk char(5),
        dbname nvarchar(128),
        cmd nchar(32),
        request_id int)
    
    go
    
    insert  #spWhoResults
    exec    sp_who
    
    
    select  *
    from    #spWhoResults
    
    /* 
    put your cursor here to loop #spWhoResults to 
    perform whatever it is you wanted to do per row
    */
    
    0 讨论(0)
  • 2020-12-19 01:03

    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
    
    0 讨论(0)
  • 2020-12-19 01:18

    Rewrite sp_who as a table function

    0 讨论(0)
提交回复
热议问题