首页 > 代码库 > 游标的使用

游标的使用

 1 declare @Id uniqueidentifier 2 declare @UserId uniqueidentifier 3 declare @DepartmentName nvarchar(128) 4 declare @DepartmentId uniqueidentifier 5 declare @departmentCount int 6 declare cursor1 cursor for select Id from PersonSummary        --定义游标cursor1 7  8  9 open cursor1    10 11 fetch next from cursor1 into @Id12 13 14 while @@fetch_status=0           --判断是否成功获取数据15 begin16 17 select @UserId=userId from PersonSummary where id=@Id18 select @departmentCount=COUNT(*) from PersonSummaryDepartment where PersonSummaryId=@Id19 if (@departmentCount <1)20     begin21         insert into PersonSummaryDepartment(PersonSummaryId,DepartmentId,DepartmentName)22         select @id,a.DepartmentId,b.Name from [RSGPMS] .dbo.DepartmentUserRef a,[RSGPMS] .dbo.Department b where  a.UserId=@UserId and a.DepartmentId = b.Id23 24     end25 fetch next from cursor1 into @Id  --将游标向下移1行26 end27 28 close cursor1                   --关闭游标29 deallocate cursor1
View Code

 

游标的使用