我创建了一个带有光标的函数来计算另一个表中的所有主菜。当我这样做PRINT dbo.cursorEnroll ();
时,当我的表中只有 10 个主菜时,我得到 11 作为输出。@@FETCH = 0 应该意味着 fetch 成功,因此应该只设置 studentsEnrolled 10 次。我很困惑这个额外的计数来自哪里。
免责声明:我知道这不是计算表中条目数的最佳方法。但是,我只是在学习和练习游标的使用。
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;