SQLTeam.com | Weblogs | Forums

Using only one Fetch Next statement...because I hate having to use two!

Not sure if I'm 100% convinced, but like many, if you hate having two Fetch Next statements then this may help.... Any other ideas?

DECLARE @FetchStatus int = 0
DECLARE MyCursor CURSOR FOR SELECT Blah Blah Blah from MyTable
OPEN MyCursor
WHILE @FetchStatus = 0  
BEGIN  
	FETCH NEXT FROM MyCursor INTO MyVariables   
	SET @FetchStatus = @@Fetch_Status
	IF @FetchStatus = 0
	BEGIN
		Do_Something_Here
	END
END
CLOSE MyCursor
DEALLOCATE MyCursor

Seems longer and more convoluted IMHO, just to avoid a pre-loop FETCH. You're doing two identical logical tests, an extra variable assignment, and an extra BEGIN...END construct.

I don't suppose Do_Something_Here can be rewritten so as not to require a cursor?

Less messy version

DECLARE MyCursor CURSOR FOR SELECT Blah Blah Blah from MyTable
OPEN MyCursor
WHILE 1 = 1
BEGIN
FETCH NEXT FROM MyCursor INTO MyVariables
IF @@Fetch_Status <> 0 BREAK
Do_Something_Here
END
CLOSE MyCursor
DEALLOCATE MyCursor