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