I have a task that I’m getting a bit hung up on with SQL Server and wondered if anybody could help.
Task:
Within the database, I need to create a stored procedure with the name ClassRegistration. The columns of the result set for this stored procedure need to be as follows:
[Class]– The name of the class to be taught[Teacher Name]– The name of the person teaching the class[Registrations]– The number of pupils who have registered to take the class[Number Paid]– The number of pupils who have paid their fees for the class
Tables:
[Teacher]:Teacher_ID(PK),TeacherName[Class]:Class_ID(PK),ClassName,Teacher_ID(FK)[ClassRegistration]Student_ID(FK),Class_ID(FK),HasPaidFees[Student]Student_ID(PK),StudentName
The college needs to know about every class, even if nobody has yet registered.
My SQL so far:
Create PROCEDURE ClassRegistration
AS
SELECT DISTINCT
c.ClassName,
t.TeacherName,
COUNT(cr.Student_ID) As Registrations,
COUNT(case when cr.HasPaidFees = 1 then 1 else null end) As NumberPaid
FROM
Class As c,
Teacher As t,
ClassRegistration As cr,
Student As s
WHERE
(c.Class_ID = cr.Class_ID)
AND (cr.Student_ID = s.Student_ID)
GROUP BY c.ClassName, t.TeacherName
I can create the stored procedure fine but the output doesn’t look correct, any help would be greatly appreciated :).
There is no reason to join to Student and you had 4 tables but only 2 join criteria. This is one of the pitfalls of using old
table,tablejoin syntax instead of proper, explicit joins. I also:dbo.prefix to table referencesSET NOCOUNT ONto the procedureDISTINCTCASEexpression