加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 如何在while循环中手动中断游标.在sql server中

发布时间:2020-12-12 07:44:42 所属栏目:MsSql教程 来源:网络整理
导读:if while loop also having a break,if while loop hit break command i t comes out of the loop and if cursor hit break command,how it come entire out of the while loop for example: DECLARE @CursorTest TABLE ( idcol INT,fld1 INT,fld2 INT,fld3
if while loop also having a break,if while loop hit break command  i t comes out of the loop and  if cursor hit break  command,how it come entire  out of the while loop

        for example: 
        DECLARE @CursorTest TABLE 
        (
        idcol INT,fld1 INT,fld2 INT,fld3 CHAR(800)
        )

        INSERT INTO @CursorTest (fld1,fld2,fld3)

        SELECT 1,RAND() * 100 * DATEPART(ms,GETDATE()),LEFT(REPLICATE(CAST(NEWID() AS VARCHAR(36)),30),800)


        DECLARE @Variable1 INT,@Variable2 INT
        DECLARE CursorName CURSOR FAST_FORWARD
        FOR
        SELECT idcol    FROM @CursorTest    
        OPEN CursorName
        FETCH NEXT FROM CursorName  INTO @Variable1
        WHILE @@FETCH_STATUS = 0
        BEGIN


            if (@Variable1 =10) 
            BEGIN
                BREAK
            END 
            PRINT CAST(@Variable1 AS VARCHAR(5))



        FETCH NEXT FROM CursorName  INTO @Variable1

        END
        CLOSE CursorName
        DEALLOCATE CursorName



    if cursor hit break  command,how it come entire  out of the while loop

如果while循环也有一个中断,如果while循环命中中断命令我退出循环并且如果光标命中break命令,它是如何完全退出while循环的

解决方法

你可以在WHILE循环中给出一些迭代光标的条件.第一个条件是@@ FETCH_STATUS,而其他条件就是你要打破循环
WHILE @@FETCH_STATUS = 0 OR @stopLoop = false
   BEGIN
      FETCH NEXT FROM Employee_Cursor;
      //your code
      if condition 
      BEGIN
          @stopLoop = true
      END 
   END;
CLOSE Employee_Cursor;

使用BREAK语句

WHILE @@FETCH_STATUS = 0 
   BEGIN
      FETCH NEXT FROM Employee_Cursor;
      //your code
      if condition 
      BEGIN
          BREAK
      END 
   END;
CLOSE Employee_Cursor;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读