T-SQL loop over query results

前端 未结 6 1624
别跟我提以往
别跟我提以往 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:22

    You could do something like this:

    create procedure test
    as
    BEGIN
    
        create table #ids
        (
            rn int,
            id int
        )
    
        insert into #ids (rn, id)
        select distinct row_number() over(order by id) as rn, id
        from table
    
        declare @id int
        declare @totalrows int = (select count(*) from #ids)
        declare @currentrow int = 0
    
        while @currentrow <  @totalrows  
        begin 
            set @id = (select id from #ids where rn = @currentrow)
    
            exec stored_proc @varName=@id, @otherVarName='test'
    
            set @currentrow = @currentrow +1
        end  
    
    END
    

提交回复
热议问题