利用游标在存储过程中做循环数据处理

本文介绍了一种在存储过程中利用游标进行循环数据处理的方法,通过示例展示如何创建并使用游标来统计用户及其委托人在特定日期范围内待审批的工作数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于以前经常被警告在使用游标的要慎重,所以一直都没有使用过它。这几天在做一个东西,突然就想试试,发现还是有它的优势的,特别是用来做循环处理,大大简化了应用程序。下面记录的是一个程序片段,主要用于描述其使用的一般方法,以供参考。

CREATE PROCEDURE [dbo].[Flow_Sel]
@Employeeno varchar(7),
@mycount int output
AS

declare @delegateno varchar(7)
--获取当前日期(不含时间)
declare @curdate smalldatetime
declare @cd datetime
set @cd = getdate()
set @curdate=cast(datepart(year,@cd) as varchar) + '-' + cast(datepart(month,@cd) as varchar)
+ '-' + cast(datepart(day,@cd) as varchar)

--此用户的待审批工作数量
set @mycount=(select count(fid) from Flow
where Employeeno=@Employeeno and status=1)

--定义一个游标,用于遍历用户所有的委托人
 declare employee_cursor  cursor for
 select Employeeno 
 from Delegate
 where @curdate>=StartDate and @curdate<=EndDate and Active=1 and Delegateno=@Employeeno

 open employee_cursor
 fetch next from employee_cursor into @delegateno
 WHILE @@FETCH_STATUS = 0
 begin
  set @mycount=@mycount+(select count(FID)  from Flow
  where Employeeno=@delegateno and Status=1)--计算委托人的所有待审批工作数量并累加到@mycount变量中
    
  fetch next from employee_cursor into @delegateno
 end
 close employee_cursor--关闭
 DEALLOCATE employee_cursor--释放
 
return
GO

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客行天下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值