首页 > 解决方案 > 将光标替换为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

标签: sqlsql-server

解决方案


首先,我不知道您声明的游标来自您的 @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 记录开始循环


推荐阅读