SQLSERVER 游标

ALTER PROCEDURE [dbo].[PROC_UpdMonthStatus]
AS
    BEGIN
        declare @a int,
        @error int,
        @Id varchar(36),
        @Area varchar(200),
        @Department varchar(200),
        @Year INT,
        @Month INT
        
        set @a=1
        set @error=0
        
         --申明游标为Uid
        declare order_cursor cursor 
        for (select Id,Area,Department,ReportYear,ReportMonth from AreaMonthReport where Status=3)
        --打开游标--
        open order_cursor
         --开始循环游标变量--
        fetch next from order_cursor into @Id,@Area,@Department,@Year,@Month
        while @@FETCH_STATUS = 0    --返回被 FETCH语句执行的最后游标的状态--
            begin
                ---添加一天办理记录            
                DECLARE @CreatorId varchar(36)
                SET @CreatorId=(select TOP 1 CreatorId from AuditOptions where AreaMonthReportId=@Id order by CreateTime desc)
                insert into AuditOptions(ID,Link,CreateUser,CreatorId,OptionText,CreateTime,AreaMonthReportId)
                values (NEWID(),'总部审核',@CreatorId,'','自动同意',GETDATE(),@Id)
                --修改ProjectMonthTrack
                update ProjectMonthTrack set ProjectStatus=5 where Area=@Area and Department=@Department and ReportYear=@Year and ReportMonth=@Month
                --修改AreaMonthReport
                update AreaMonthReport set Status=5 where Id=@Id
                
                
                set @a=@a+1
                set @error= @error + @@ERROR   --记录每次运行sql后是否正确,0正确
                fetch next from order_cursor into @Id,@Area,@Department,@Year,@Month   --转到下一个游标,没有会死循环
            end   
    

    close order_cursor --关闭游标
    deallocate order_cursor -- 释放游标

 
    END
GO

以上代码主要实现了一条添加,以及2条修改记录

posted @ 2018-07-10 11:41  桎梏110  阅读(241)  评论(0编辑  收藏  举报
Live2D