I have to create a stored procedure wher Input for the stored procedure will be Course Id and Student Id. The stored procedure will check if the student is enrolled in the class yet. If the student has already been enrolled, display a message that says “The student is already enrolled”.
Below is what I tried. Did not get the result as expected. tables that i have:
this is what I tried
CREATE PROCEDURE Clk (@CourseId AS INTEGER, @StudentId AS VARCHAR) AS
DECLARE @stud INTEGER
SELECT @stud = (select Count(enrollmentId) from CourseEnrollment
where StudentId = @StudentId and CourseId = @CourseId )
if @stud > 0
BEGIN
print 'The student is already enrolled'
END
else
BEGIN
print 'nope'
END
EDITIED:
I got it working now. I had given data type wrong while creating the stored procedures.
You haven't taken into consideration CourseId when filtering the records. Your query:
SELECT @stud = (select Count(enrollmentId)
from CourseEnrollment
where StudentId = @StudentId )
If you have passed say course 1 for student xyz, and if xyz has enrolled for course 2, then you query will give result as 1 and even though he is not enrolled for course 1, you will say that he has enrolled for the same.
Try something like:
IF EXISTS (SELECT CourseId
FROM courseEnrollment
WHERE StudentId = @StudentId
AND CourseId = @CourseId) THEN
print 'The student is already enrolled'
ELSE
print 'The student has not enrolled'
END IF;