how to avoid the cursor statement to execute if no records are retunred
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 anywa开发者_如何学Pythony. 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?
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
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?
精彩评论