简体   繁体   中英

How to create a stored procedure with "IF statements"?

Plese help me with this stored procedure problem 1. Create the following table

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

Create a procedure that can insert into tblEnrolled with the following conditions and response

a. If the student number does not exist, do not insert, response: Student Number does not exist.

b. If the subject code does not exist, do not insert, response: Subject Code does not exist.

c. If the student number is already graded in the given subject code with passing grade (including INC, 4.00), do not insert, response: Student already passed the given subject.

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, response: New record added.

I dont know the next steps:

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);

?????

This will get you a little closer:

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 ;

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