I created a function with a cursor to count all the entrees in my other table.
When I do PRINT dbo.cursorEnroll ();
I get 11 as an output when I only had 10 entrees in my table.
@@FETCH = 0 should mean fetch is successful, and thus should only SET studentsEnrolled 10 times. I am confused where this extra count comes from.
DISCLAIMER: I know this isn’t the best way to count the number of entries in a table. However, I am just learning and practicing the use of cursors.
CREATE FUNCTION dbo.cursorEnroll ()
RETURNS INT AS
BEGIN
DECLARE @studentsEnrolled INT
SET @studentsEnrolled = 0
DECLARE myCursor CURSOR FOR
SELECT enrollementID
FROM courseEnrollment
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @studentsEnrolled
WHILE @@FETCH_STATUS = 0
BEGIN
SET @studentsEnrolled = @studentsEnrolled+1
FETCH NEXT FROM myCursor INTO @studentsEnrolled
END;
CLOSE myCursor
RETURN @studentsEnrolled
END;
Because you fetch
enrollementIDinto@studentsEnrolledand then add 1. For last rowenrollementID = 10then you get 11 as result.