• Figured it out... I was joining on the wrong column in the CTE...

    -- courses without prereqs

    WITH PrereqsCTE (CourseID, Depth) AS

    (

    --- Anchor: courses without prerequisites

    SELECT c.CourseID, 0 AS Lvl

    FROM Course c

    WHERE NOT EXISTS (SELECT * FROM Prereq WHERE NextCourseID = c.CourseID)

    UNION ALL

    -- Recursive member: courses that have other courses as prerequisites.

    SELECT p.NextCourseID, Depth + 1

    FROM Prereq p INNER JOIN PrereqsCTE

    ON p.ReqCourseID = PrereqsCTE.CourseID

    )

    SELECT CourseID, Depth

    FROM PrereqsCTE;