Loop on results, call sproc

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    Loop on results, call sproc

    Hi,
    I'm looking for a way to loop on a set of temporary results and run a stored procedure on each row of the results.

    Simplified code of what I'm trying to do:
    [code=sql]
    Declare @TMP TABLE
    (
    field1 Int
    field2 Int
    )

    INSERT INTO @TMP
    SELECT id, otherVar
    from ....blah join blah join blah
    where bar = foo


    Declare @RC = int
    -- Want to loop here.
    For each result.
    Exec @RC = [Process].[dbo].[usp.storedProc1] **field1** **field2**
    End for
    [/code]

    What is the syntax to do this? Also is this terminology correct, or is there another specific word for what I'm looking for?
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Finally managed to find a solution:
    [code=sql]
    Declare @TMP TABLE
    (
    field1 Int
    field2 Int
    )

    INSERT INTO @TMP
    SELECT id, otherVar
    from ....blah join blah join blah
    where bar = foo


    Declare @RC = int
    Declare @f1 = int
    Declare @f2 = int
    declare cur_1 cursor for select field1, field2 from @TMP

    -- like a do-while
    fetch next from cur_1 into @f1, @f2;
    while @@FETCH_STATUS = 0
    begin
    Exec @RC = [Process].[dbo].[usp.storedProc1] @f1, @f2
    fetch next from cur_1 into @f1, @f2;
    end
    close cur_1;
    [/code]

    Comment

    Working...