简体   繁体   English

关于存储过程中的查询

[英]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. 我必须创建一个存储过程,该存储过程的输入将是“课程ID”和“学生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. 在过滤记录时,您没有考虑CourseId。 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. 如果您已经通过了说给学生xyz的课程1,并且xyz已经注册了课程2,则您的查询将给出结果为1,即使他没有被课程1录取,您也会说他也已经注册了课程。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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