如何使用“ IF语句”创建存储过程?

时间:2019-11-27 14:50:22

标签: sql mariadb delimiter

请帮助我解决此存储过程问题 1.创建下表

CREATE TABLE tblEnrolled
(
    id INT(11) AI PK,
    studNum VARCHAR(9),
    subjCode VARCHAR(20)
)

创建一个程序,该程序可以insert into tblEnrolled并具有以下条件和响应

a。如果学生编号不存在,请不要插入,回复:学生编号不存在。

b。如果主题代码不存在,请不要插入,回复:主题代码不存在。

c。如果学生编号已经在给定的科目代码中通过及格分数(包括INC,4.00)进行评分,则不要插入,回复:学生已通过给定的科目。

d。如果学生编号和学科代码在tblGrade表中不存在,或者在tblGrade表中,但成绩不及格,则插入记录,并回答:添加了新记录。

我不知道下一步:

CREATE TABLE tblEnrolled (id INT(11) AUTO_INCREMENT PRIMARY KEY, studNum VARCHAR(9), subjCode VARCHAR(20));
DELIMITER $$
CREATE PROCEDURE grade(IN studNum VARCHAR(9), IN subjCode VARCHAR(20))
RETURNS VARCHAR (50)
DETERMINISTIC
BEGIN
DECLARE r VARCHAR(50);

?????

1 个答案:

答案 0 :(得分:0)

这将使您更近一些:

CREATE TABLE tblEnrolled (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    studNum VARCHAR(9),
    subjCode VARCHAR(20)
);

DELIMITER $$

CREATE PROCEDURE grade(IN _studNum VARCHAR(9), IN _subjCode VARCHAR(20))
    RETURNS VARCHAR (50)
    DETERMINISTIC
BEGIN
    IF (_studNum IS NULL)
    THEN -- a. If the student number does not exist, do not insert,
        SELECT "Student Number not supplied.";
    ELSE IF (_subjCode IS NULL)
    THEN  --  b. If the subject code does not exist, do not insert, response: 
        SELECT "Subject Code does not exist.";
    ELSE IF ( EXISTS( SELECT 1 FROM tbl WHERE ... ) )
    THEN -- c. If the student number is already graded in the given subject code with passing grade (including INC, 4.00), do not insert, response: 
        SELECT "Student already passed the given subject.";
    ELSE BEGIN
        SET @sql = "SELECT grade INTO @grade FROM tblGrade WHERE student_num = ?";
        PREPARE _SQL FROM @sql;
        EXECUTE _SQL, _student_num;
        DEALLOCATE PREPARE _SQL;
        IF @grade IS NULL OR @grade < 1.0
        THEN  -- d. If the student number and subject code do not exist in the tblGrade table or it is in the tblGrade table but with failing grade, insert the record,
            BEGIN
                INSERT INTO ...;
                SELECT "New record added.";
            END;
        END IF;
    END;
END $$

DELIMITER ;