sql - 将光标替换为while循环但不起作用
问题描述
请帮我。由于性能问题,我已将 Curser 更改为 While 循环。
但是我的 while 循环不起作用,实际上它比平时花费的时间更长,而且它似乎是无限循环,请让我知道我在这里做错了什么。
使用 Curser - 工作正常
DECLARE policyVerify_cursor CURSOR LOCAL FOR
Select AccountId, PolicyNumber, IsPolicyBalance, Remarks from @VerifyPolicyNumbers
-- Open cursor
OPEN policyVerify_cursor
FETCH NEXT FROM policyVerify_cursor INTO @AccountId, @PolicyNumber, @IsPolicyBalance, @Remarks
WHILE (@@FETCH_STATUS= 0)
BEGIN
-- my LOGIC
FETCH NEXT FROM policyVerify_cursor
INTO @AccountId, @PolicyNumber, @IsPolicyBalance, @Remarks
END
我的查询使用 While 循环 - 不工作
DECLARE @NumberRecords int, @RowCounter int
SET @NumberRecords = (SELECT COUNT(*) FROM @VerifyPolicyNumbers)
SET @RowCounter = 1
-- loop through all records in the temporary table
-- using the WHILE loop construct
WHILE @RowCounter <= @NumberRecords
BEGIN
-- My Logic
SET @RowCounter = @RowCounter + 1
END
解决方案
首先,我不知道您声明的游标来自您的 @VerifyPolicyNumbers 表来自哪里。此外,如果 @VerifyPolicyNumbers 表是您在执行逻辑时添加的内容,这是否会导致一些问题......在您声明列表后有更多记录?
您可能希望使用“#”将查询拉入 TEMPORARY SESSION 表并从中进行查询,这样您就不会遇到我首先描述的可能场景。然后调整类似
select
AccountId,
PolicyNumber,
IsPolicyBalance,
Remarks
into
#myTempList
from
@VerifyPolicyNumbers
DECLARE policyVerify_cursor CURSOR
-- declaring the cursor for SCROLLING THROUGH RECORDS
SCROLL FOR
Select
AccountId,
PolicyNumber,
IsPolicyBalance,
Remarks
from
#myTempList
-- Open cursor
OPEN policyVerify_cursor
-- explicitly select FIRST record
FETCH FIRST FROM policyVerify_cursor INTO
@AccountId, @PolicyNumber, @IsPolicyBalance, @Remarks
WHILE (@@FETCH_STATUS= 0)
BEGIN
-- my LOGIC
-- Now, get the NEXT record.
FETCH NEXT FROM policyVerify_cursor
INTO @AccountId, @PolicyNumber, @IsPolicyBalance, @Remarks
END
CLOSE policyVerify_cursor
DEALLOCATE policyVerify_cursor
它可能会失败,因为您没有声明游标 FOR SCROLL,还 FETCHING FIRST 记录开始循环
推荐阅读
- c# - 取一组数字,将它们平均分成 3 个新组
- javascript - 无法在我的 todoList 中读取对象值
- javascript - 如何正确多次调用firebase
- php - “CORS:不存在‘Access-Control-Allow-Origin’标头”,但存在
- apache - apache nifi中GETftp处理器中的路径过滤器正则表达式
- python - plotly dash 将图像添加到 dcc.Tabs,根据用户输入进行更新
- javascript - 将嵌入消息编辑为简单文本 discord.js
- c++ - 从 C++ 字符串中删除元音
- c# - 有没有办法将数组中的数据保存到文本文件中
- python - 每次运行程序时如何创建新文件?