如何在while循环中手动中断光标?
Posted
技术标签:
【中文标题】如何在while循环中手动中断光标?【英文标题】:How to manually break the cursor within a while loop? 【发布时间】:2015-04-06 06:24:49 【问题描述】:如果while循环命中break命令退出循环,如果光标命中break命令,如何完全退出while循环?
例如:
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
【问题讨论】:
【参考方案1】:您可以在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;
【讨论】:
不会是 WHILE @@FETCH_STATUS = 0 AND @stopLoop = false 而不是 OR ?以上是关于如何在while循环中手动中断光标?的主要内容,如果未能解决你的问题,请参考以下文章
为啥这个 switch 语句在运行时会结束 while 循环?