gotchasqlModerate
What's the difference between fetch and fetch next?
Viewed 0 times
thewhatfetchnextdifferencebetweenand
Problem
I've got a cursor sending out pager messages, and occasionally it sends out duplicates. The syntax looks like this:
Question: if I'm getting duplicates, could it be the fetches? do they both need to be fetch next, or neither?
declare @col1 varchar(255),
@col2 varchar(255)
declare c cursor local for
select column1, column2
from table
where flippity = 'floppity'
open c
fetch from c into @col1, @col2
While @@FETCH_STATUS = 0
begin
sp_do_your_thing @col1, @col2
fetch next from c into @col1, @col2
end
close c
deallocate cQuestion: if I'm getting duplicates, could it be the fetches? do they both need to be fetch next, or neither?
Solution
There is no difference, and omitting
I would look at the query, as I suspect it will also be returning duplicates when there is no cursor involved. Or, whatever the stored procedure is doing, is making it seem like there are duplicates. Another possible explanation is if the query is using
NEXT will not lead to duplicates or different results in any way. NEXT is just an explicit declaration of the default behavior. From the syntax diagram:FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROMNEXT is not the only option, and most of the other options are only available with certain types of cursors. It's hard for me to get into this habit, because I exclusively use fast-forward, single-pass, "firehose" cursors, but best practice is to include NEXT explicitly.I would look at the query, as I suspect it will also be returning duplicates when there is no cursor involved. Or, whatever the stored procedure is doing, is making it seem like there are duplicates. Another possible explanation is if the query is using
WITH (NOLOCK) / READUNCOMMITTED and you are reading the same row twice in an allocation order scan due to data movement.Code Snippets
FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROMContext
StackExchange Database Administrators Q#204712, answer score: 11
Revisions (0)
No revisions yet.