T-SQL loop over query results

前端 未结 6 1641
别跟我提以往
别跟我提以往 2020-11-27 10:40

I run a query select @id=table.id from table and I need to loop over the results so I can exec a store procedure for each row exec stored_proc @varName=@i

6条回答
  •  时光取名叫无心
    2020-11-27 11:21

    try this:

    declare @i tinyint = 0,
        @count tinyint,
        @id int,
        @name varchar(max)
    
    select @count = count(*) from table
    while (@i < @count)
    begin
        select @id = id, @name = name from table
        order by nr asc offset @i rows fetch next 1 rows only
    
        exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name
    
        set @i = @i + 1
    end
    

提交回复
热议问题