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

前端之家收集整理的这篇文章主要介绍了sql-server – 如何在while循环中手动中断游标.在sql server中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 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
  2.  
  3. for example:
  4. DECLARE @CursorTest TABLE
  5. (
  6. idcol INT,fld1 INT,fld2 INT,fld3 CHAR(800)
  7. )
  8.  
  9. INSERT INTO @CursorTest (fld1,fld2,fld3)
  10.  
  11. SELECT 1,RAND() * 100 * DATEPART(ms,GETDATE()),LEFT(REPLICATE(CAST(NEWID() AS VARCHAR(36)),30),800)
  12.  
  13.  
  14. DECLARE @Variable1 INT,@Variable2 INT
  15. DECLARE CursorName CURSOR FAST_FORWARD
  16. FOR
  17. SELECT idcol FROM @CursorTest
  18. OPEN CursorName
  19. FETCH NEXT FROM CursorName INTO @Variable1
  20. WHILE @@FETCH_STATUS = 0
  21. BEGIN
  22.  
  23.  
  24. if (@Variable1 =10)
  25. BEGIN
  26. BREAK
  27. END
  28. PRINT CAST(@Variable1 AS VARCHAR(5))
  29.  
  30.  
  31.  
  32. FETCH NEXT FROM CursorName INTO @Variable1
  33.  
  34. END
  35. CLOSE CursorName
  36. DEALLOCATE CursorName
  37.  
  38.  
  39.  
  40. if cursor hit break command,how it come entire out of the while loop

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

解决方法

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

使用BREAK语句

  1. WHILE @@FETCH_STATUS = 0
  2. BEGIN
  3. FETCH NEXT FROM Employee_Cursor;
  4. //your code
  5. if condition
  6. BEGIN
  7. BREAK
  8. END
  9. END;
  10. CLOSE Employee_Cursor;

猜你在找的MsSQL相关文章