在 Microsoft SQL Server 中循环使用游标

Using cursors in Microsoft SQL Server with a loop

问题:

Write a script that determines if too few students (less than five) or too many students (greater than 10) are enrolled in each course. To do that, you can use a cursor. This cursor should use a SELECT statement that gets the CourseID and the count of students for each course from the StudentCourses table.

When you loop through the rows in the cursor, the script should display a message like this if there are too few students enrolled in a course:

"Too few students enrolled in course x" where x is the course ID. The script should display a similar message if there are too many students enrolled in a course.

到目前为止我的代码:

DECLARE Students_Cursor CURSOR FOR 
    SELECT c.CourseID, COUNT(sc.StudentID) 
    FROM Courses c 
    JOIN StudentCourses sc ON c.CourseID = sc.CourseID
    WHERE COUNT(sc.StudentID) < 5  OR COUNT(sc.StudentID) > 10

OPEN Student_Cursor;

FETCH NEXT FROM Students_Cursor

WHILE @@FETCH_STATUS <> -1
BEGIN
    IF 

使用 CURSOR 通常比更好的替代选项慢。也就是说,您需要做的第一件事就是让 SELECT 语句正常工作。我不认为它会像你拥有的那样工作。如果您使用的是 COUNT,那么您就是在聚合。如果您想按聚合过滤结果,则不能使用 WHERE 子句。相反,您需要将其移至 HAVING 子句中。此外,由于您选择的不仅仅是聚合计数,因此您需要按 CourseID 进行分组。要继续这条路线,您将有一个 SELECT 像:

SELECT c.CourseID, COUNT(sc.StudentID) FROM Courses c JOIN StudentCourses sc
ON c.CourseID= sc.CourseID
GROUP BY c.CourseID
HAVING COUNT(sc.StudentID) < 5  OR COUNT(sc.StudentID) > 10;

并不是说在 CURSOR 中限制您要 运行 通过的行数是个坏主意,但是如果您要在 CURSOR 中检查学生人数,也许他们正在寻找您在 CURSOR 本身中执行逻辑。您可以只删除 HAVING 子句并遍历 CURSOR 中的所有行。

理清 SELECT 并从 CURSOR 获取 FETCH 后,您希望将 SELECT 的项目拉入变量,然后您可以使用它们来生成消息。因此,您想早点声明它们,然后将 CURSOR 值拉入其中。像

FETCH NEXT FROM Students_Cursor INTO @CourseID, @StudentCount;
WHILE @@FETCH_STATUS <> -1

然后您可以对@StudentCount 执行IF/THEN 条件,并在消息中使用@CourseID。只需确保在那之后,您再次将 FETCH NEXT FROM 放入 BEGIN/END 块内的变量中,然后当然关闭并取消分配 CURSOR。