关于存储过程中的查询

时间:2015-03-22 12:45:28

标签: mysql sql database stored-procedures rdbms

我必须创建一个存储过程,其中存储过程的输入将是Course Id和Student Id。 存储过程将检查学生是否已在该课程中注册。 如果学生已经注册,则会显示一条消息“学生已经注册”。

以下是我的尝试。没有按预期得到结果。 我有的表:

enter image description here

enter image description here enter image description here

这是我试过的

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:

我现在就开始工作了。我在创建存储过程时给出了错误的数据类型。

1 个答案:

答案 0 :(得分:0)

过滤记录时,您还没有考虑过CourseId。您的查询:

SELECT @stud = (select Count(enrollmentId) 
                from CourseEnrollment 
                where  StudentId = @StudentId )

如果你已经通过课程1为学生xyz说,如果xyz已经注册了课程2,那么你查询将结果为1,即使他没有注册课程1,你会说他已注册同样的。

尝试类似:

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;