重置@@FETCH_STATUS存储过程
如何在存储过程中重置 @@FETCH_STATUS
变量或将其设置为 0?
另外,您可以将 FETCH_STATUS 绑定到特定游标吗?
How can I reset the @@FETCH_STATUS
variable or set it to 0 in a stored procedure?
Also, can you bind FETCH_STATUS to a particular cursor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我认为需要重置光标。
我正在使用游标进行一些测试,并且我不断返回 @@fetch_status = -1,即使在我对正在测试的游标编写了关闭和释放代码之后也是如此。
发生的情况是,我在逻辑测试后在另一个过程中打开了一个全局游标,并且在迭代它之后从未关闭该游标。
所以 Fetch 看到了该游标的 @@Fetch_status。
关闭光标,释放光标。
I had what I thought was a need to reset my cursor.
I was doing some testing with cursors and I kept coming back with a @@fetch_status being = -1, even after I had coded a close and deallocation to the cursor I was testing.
What had happened was I had opened a global cursor in another procedure after a logical test and never closed that cursor after iterating through it.
So the Fetch was seeing the @@Fetch_status of that cursor.
Close your cursors, deallocate your cursors.
如果你想打破光标你可以使用BREAK
但这只是将函数从0替换为1。
If you want to break cursor You can use BREAK
But this only only replace function from 0 to 1.
通常,在 FETCH 之后立即会出现 @@FETCH_STATUS,那么为什么要重置它呢?
如果不立即求值,请尝试将其结果存储在临时变量中。
Typically you have a @@FETCH_STATUS immediately after a FETCH, so why would you want to reset it?
Try to store its result in a temporary variable if you do not evaluate immediately.
你不能:
所以基本上它不绑定到任何光标。
You can't:
So basically it's not bound to any cursor.
我知道一个旧线程,但在其他地方找到的对我有用的答案是:
An old thread I know but an answer found elsewhere that worked for me was:
您需要关闭光标,然后再次打开光标。
You need to close the cursor and then Open the cursor again.
您可以通过读取不在表末尾的游标来重置它。
You can reset it by reading a cursor which is not at the end of a table.
我能够重现
@@FETCH_STATUS
您描述的问题,这是一旦您DECLARE
一个CURSOR
并通过调用FETCH NEXT
迭代行,直到您的@@FETCH_STATUS = -1
。那么即使您
CLOSE
并DEALLOCATE
您的光标,如果您将该CURSOR
调用回您的@@FETCH_STATUS = -1
并且如果您的循环条件基于@@FETCH_STATUS <> -1
,你的循环永远不会执行。我的解决方案基本上是告诉
CURSOR
返回到FIRST
,将@@FETCH_STATUS
更改回0
,然后退出。 请注意,在声明CURSOR
名称后,必须通过在CURSOR
名称后面添加关键字SCROLL
来使CURSOR
能够滚动。这是一个例子。 我使用 orderitems(人们下订单的商品)表中的三列来创建游标:
这些是结果:
游标可以反复运行,每次都会产生相同的结果。
I am able to reproduce the
@@FETCH_STATUS
issue you describe, this is once youDECLARE
aCURSOR
and iterate through the rows by callingFETCH NEXT
until your@@FETCH_STATUS = -1
.Then even if you
CLOSE
andDEALLOCATE
your cursor, if you call thatCURSOR
back your@@FETCH_STATUS = -1
and if your basing a loop condition on the@@FETCH_STATUS <> -1
, your loop never executes.My solution was to basically tell the
CURSOR
to go back toFIRST
, changing the@@FETCH_STATUS
back to0
, then exiting. Take note that one must enable toCURSOR
to be scrolling by adding the keywordSCROLL
after theCURSOR
name when you declare it.Here's an example. I used three columns from an orderitems (items people placed orders for) table to create my cursor:
These are the results:
The cursor can be run over and over and will product the same results each time.