set serveroutput on size 32000

-- Print the names of students taking a specific class.
CREATE OR REPLACE PROCEDURE students_in_class(class_name IN Enrolled.cname%TYPE) AS
stu_number Enrolled.snum%TYPE;
stu_name Student.sname%TYPE;
CURSOR enr_cur IS SELECT snum FROM Enrolled WHERE cname=class_name;
enr_rec enr_cur%ROWTYPE;
BEGIN
    FOR enr_rec IN enr_cur LOOP
        stu_number := enr_rec.snum;
        SELECT sname INTO stu_name FROM Student WHERE snum=stu_number;
        dbms_output.put_line(stu_name);
    END LOOP;
END students_in_class;
/

-- Insert a given faculty into the database.
-- CREATE OR REPLACE PROCEDURE insert_faculty(faculty IN Faculty%ROWTYPE) AS
CREATE OR REPLACE PROCEDURE insert_faculty(fid IN Faculty.fid%TYPE, fname IN Faculty.fname%TYPE, deptid IN Faculty.deptid%TYPE) AS
BEGIN
    -- INSERT INTO Faculty VALUES faculty;
    INSERT INTO Faculty VALUES(fid, fname, deptid);
END insert_faculty;
/

-- For each department, print the average age of students in that department.
CREATE OR REPLACE PROCEDURE average_age_by_dept AS
    avg_age NUMBER;
    num_students NUMBER;
    dept Department.dname%TYPE;
    CURSOR dept_cur IS SELECT DISTINCT deptid FROM Student;
    CURSOR age_cur(did IN Student.deptid%TYPE) IS SELECT age FROM Student WHERE deptid = did;
    dept_rec dept_cur%ROWTYPE;
    age_rec age_cur%ROWTYPE;
BEGIN
    FOR dept_rec IN dept_cur LOOP
        avg_age := 0;
        num_students := 0;
        FOR age_rec IN age_cur(dept_rec.deptid) LOOP
            avg_age := avg_age + age_rec.age;
            num_students := num_students + 1;
        END LOOP;
        avg_age := avg_age / num_students;
        SELECT dname
            INTO dept
            FROM Department
            WHERE deptid = dept_rec.deptid;
        dbms_output.put_line(dept || ' ' || avg_age);
    END LOOP;
END average_age_by_dept;
/

DELETE FROM Faculty F WHERE F.fname = 'Adams';

BEGIN
    students_in_class('ENG40000');
    students_in_class('CS448');
    students_in_class('STAT11000');
    insert_faculty(1100,'Adams',66);
    average_age_by_dept;
END;
/

SELECT * FROM Faculty;

