SQLserver 使用游标双重循环生成新的数据表内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/upi2u/article/details/84298442

begin
    declare @a int,@error int    
    declare @temp varchar(50), @temp2 varchar(50)
    set @a=1
    set @error=0
    
    --创建临时表
    Create Table Rpt_customerMoney (customerId int, customer varchar(30), supplierId int, supplier varchar(30), receiveSum float) ;
    
    --申明游标为Uid
    declare order_cursor cursor 
            for (select [id] from customer)
    --打开游标--
    open order_cursor
    
    --开始循环游标变量--
    fetch next from order_cursor into @temp
    while @@FETCH_STATUS = 0    --返回被 FETCH语句执行的最后游标的状态--
        begin            
        
            print @temp;
        
            --申明游标为Uid
            declare order_cursor2 cursor 
                    for (select [id] from supplier where ifOurCompany=1)
            --打开游标2--
            open order_cursor2

            fetch next from order_cursor2 into @temp2
            while @@FETCH_STATUS = 0    --返回被 FETCH语句执行的最后游标的状态--
                begin
                    insert into Rpt_customerMoney (customerId, supplierId) values (@temp, @temp2);
                    print @temp + ' '+ @temp2
            
                    fetch next from order_cursor2 into @temp2   --转到下一个游标,没有会死循环
                            
                end  
                close order_cursor2            --关闭游标
                deallocate order_cursor2    --释放游标

          
            fetch next from order_cursor into @temp   --转到下一个游标,没有会死循环
        end
        
    close order_cursor  --关闭游标
    deallocate order_cursor   --释放游标
   
end
go

猜你喜欢

转载自blog.csdn.net/upi2u/article/details/84298442