【问题标题】:How to get the last iteration in cursor prematurely?如何过早地获得游标中的最后一次迭代?
【发布时间】:2016-08-25 09:03:12
【问题描述】:

如何提前获取游标中的最后一次迭代以将其与值进行比较并在满足条件时中断。

OPEN lcr_trans   
    FETCH NEXT FROM lcr_trans INTO @trans_time , @machine_id , @trans_camp_code;
    WHILE @@FETCH_STATUS = 0   
    BEGIN
    IF(cast(@shift_start_time as time)<>'00:00:00.0000000'  AND (cast(@shift_end_time as time)<>'00:00:00.0000000' )  )
    BEGIN

      SELECT  TOP 1 @CompareWeekend= transtime_out from overtime where emp_num = @emp_num and trans_date = @previous_date;

      IF(@CompareWeekend  = @trans_time)
        BEGIN
            BREAK;
        END
    END
    -- The Cursor --
    --   ----     --
        FETCH NEXT FROM lcr_trans INTO @trans_time , @machine_id , @trans_camp_code;
    END 
    close lcr_trans;
    DEALLOCATE lcr_trans; 

我希望迭代中的最后一个 @trans_time 与我的变量 .@CompareWeekend 进行比较

【问题讨论】:

  • 你不能检查一下光标外的条件吗?为您节省一些时间和 I/O。

标签: sql sql-server database sql-server-2012 cursor


【解决方案1】:

试试这个:

declare @last_trans_time datetime, @last_machine_i varchar(max), @last_trans_camp_code varchar(max);
    OPEN lcr_trans   
        FETCH LAST FROM lcr_trans INTO @last_trans_time , @last_machine_i , @last_trans_camp_code;

        FETCH NEXT FROM lcr_trans INTO @trans_time , @machine_id , @trans_camp_code;
        WHILE @@FETCH_STATUS = 0   
        BEGIN
           IF(cast(@shift_start_time as time)<>'00:00:00.0000000'  AND (cast(@shift_end_time as time)<>'00:00:00.0000000' )  )
           BEGIN

             SELECT  TOP 1 @CompareWeekend= transtime_out from overtime where emp_num = @emp_num and trans_date = @previous_date;

             IF(@CompareWeekend  = @trans_time)
             BEGIN
               BREAK;
             END
           END
           FETCH NEXT FROM lcr_trans INTO @trans_time , @machine_id , @trans_camp_code;
        END 
   CLOSE lcr_trans;
   DEALLOCATE lcr_trans; 

您可以在此处阅读有关游标的更多信息: https://msdn.microsoft.com/en-us/library/ms180152.aspx

【讨论】:

    【解决方案2】:

    您可以使用LAST 关键字(source)获取游标中的最后一行:

    FETCH LAST FROM lcr_trans INTO @trans_time , @machine_i , @trans_camp_code;
    

    【讨论】:

    • 如何在我的上下文中使用它?我只想在 if 条件中使用它,以免混淆循环
    • 如果您使用SCROLL 选项声明CURSOR,您可以先检查最后一条记录的条件,然后返回FIRST 记录。 Check the remarks here
    • 你能用你的部分重写我的光标吗
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多