简体   繁体   中英

Regarding query in stored procedure

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM