如何过早地在光标中进行最后一次迭代?

时间:2016-08-25 09:03:13

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

如何过早地在光标中进行最后一次迭代,将其与值进行比较,如果满足条件则中断。

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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:1)

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

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