如果没有返回记录,如何避免执行游标语句

发布于 2024-11-01 03:45:56 字数 883 浏览 2 评论 0原文

我有一个嵌套游标,其 select 语句有时会返回 0 条记录。

游标执行插入语句。

我希望如果查询返回 0 条记录,则不会执行插入语句。但无论如何它都会被执行。您能建议一种方法来避免这种情况吗?

    declare  nested_cursor CURSOR 
    FOR 
    SELECT MyRECORD 

    FROM MyTable
    WHERE MyRECORD = @ID -- @ID is a variable defined in the main cursor
    -- for some values of @iD ht above select statement may return zero records
    OPEN nested_cursor
    FETCH NEXT FROM nested_cursor INTO @NestedID
    WHILE (@@fetch_status = 0)
    BEGIN  


        INSERT STATEMENT  -- HERE I HAVE THE PROBLEM , why this executes?                 
        FETCH NEXT FROM nested_cursor INTO @NestedID
    END
    CLOSE nested_cursor
    DEALLOCATE nested_cursor

更新:我通过检查 INSERT 语句之前的 @NestedId 是否为 null 找到了解决方法。

你有什么建议?添加此检查

WHILE (@@fetch_status = 0) and (@NestedID is not null)

还是有更好的技术?

I have a nested cursor whose select statement sometimes returns 0 records.

The cursor executes an insert statement.

I'd expect that the insert statement is not executed if the query returns 0 records. But it is executed anyway. Could you suggset a way to avoid this?

    declare  nested_cursor CURSOR 
    FOR 
    SELECT MyRECORD 

    FROM MyTable
    WHERE MyRECORD = @ID -- @ID is a variable defined in the main cursor
    -- for some values of @iD ht above select statement may return zero records
    OPEN nested_cursor
    FETCH NEXT FROM nested_cursor INTO @NestedID
    WHILE (@@fetch_status = 0)
    BEGIN  


        INSERT STATEMENT  -- HERE I HAVE THE PROBLEM , why this executes?                 
        FETCH NEXT FROM nested_cursor INTO @NestedID
    END
    CLOSE nested_cursor
    DEALLOCATE nested_cursor

UPDATE: I found a workaround by checking if @NestedId is null just before the INSERT statement.

WHat do you suggest? to add this check in

WHILE (@@fetch_status = 0) and (@NestedID is not null)

or there is a better technique?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

老娘不死你永远是小三 2024-11-08 03:45:56

我添加了一条评论,但是,将在答案中重做选择,以便我可以使用代码格式使其更清晰。

insert statement (myrecord) 
select myrecord 
from mytable where myrecord = @id

I added a comment but, will redo the select in the answer so that I can use the code formatting to make it clearer.

insert statement (myrecord) 
select myrecord 
from mytable where myrecord = @id
回忆追雨的时光 2024-11-08 03:45:56

它应该像你所展示的那样工作。正如其他人所说,光标似乎没有必要。

您可以尝试在 OPEN 语句后检查 @@CURSOR_ROWS 。作为替代方案,也许它返回行,但出乎意料的是,MyRecord 列为空,或者其他一些意外值?

It should be working as you've shown it. And as others have said, a cursor seems unnecessary.

You might try checking @@CURSOR_ROWS after your OPEN statement. As an alternative, maybe it is returning rows, but unexpectedly, the MyRecord column is null, or some other unexpected value?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文