标签:游标的嵌套用法
其实存储过程就是对数据库的使用的扩充,有时候我们使用SQL无法完成一些复杂逻辑,就只能靠过程了,游标又是模拟C++,Java等语言按行处理的思路,不同于SQL按集合处理的思路,
有时候我们需要游标嵌套,其实就类似于鱼 for()
for()
类似这样的嵌套循环,还是非常简单的,下面看个示例
CREATE PROCEDURE [dbo].[SP_reportEcert] AS BEGIN declare @id_owner varchar(20),@ownername varchar(20), @mcertid varchar(20), @mgrarea varchar(20), @mcertstate varchar(20), @contactor varchar(20), @address varchar(20), @origorgan varchar(20), @countVehicle integer create table #TMP (ownername varchar(20), mcertid varchar(20), mgrarea varchar(20), mcertstate varchar(20), contactor varchar(20), address varchar(20), origorgan varchar(20), countVehicle integer) DECLARE C1 CURSOR FOR select top 100 id_owner,ownername,mcertid,mgrarea,mcertstate,contactor,address,origorgan from t_owner --外层循环 OPEN C1 FETCH NEXT FROM C1 INTO @id_owner ,@ownername ,@mcertid ,@mgrarea ,@mcertstate,@contactor ,@address ,@origorgan ; WHILE @@fetch_status = 0 --循环条件(类似while true) begin DECLARE c2 CURSOR FOR select count(*) from t_vehicle where id_owner = @id_owner; OPEN C2 --外层 FETCH NEXT FROM C2 INTO @countVehicle; WHILE @@fetch_status = 0 begin insert into #TMP values(@ownername ,@mcertid ,@mgrarea ,@mcertstate,@contactor ,@address ,@origorgan ,@countVehicle); FETCH NEXT FROM C2 INTO @countVehicle; end close c2 DEALLOCATE c2 FETCH NEXT FROM C1 INTO @id_owner ,@ownername ,@mcertid ,@mgrarea ,@mcertstate,@contactor ,@address ,@origorgan ; end close c1 DEALLOCATE c1 select * from #TMP; END
本文出自 “数据领域” 博客,请务必保留此出处http://charlist.blog.51cto.com/1616209/1697391
标签:游标的嵌套用法
原文地址:http://charlist.blog.51cto.com/1616209/1697391