如何创建将记录从一个表插入到另一个表并同时检查其有效性的过程? PL / SQL

问题描述 投票:1回答:2

我在弄清楚如何成功创建此过程时遇到了麻烦,甚至不确定我是否在正确的起点上。

create or replace procedure enroll_student2(p_stu_ID number,p_class_id number)
as
declare
    stu_standing number;
    course_standing number;
begin
    if stu_standing >= course_standing THEN
        insert into enroll (stu_ID,class_id)
        select stu_id,class_id
        from student,class_sched
        where stu_id=p_stu_ID and class_id=p_class_id;
    else
        DBMS_OUTPUT.PUT_LINE('Requirement not met');
    end if;
END;
/

我正在尝试让学生入学,同时还要检查他们的学生成绩是否等于或高于课程成绩。Reference of data

sql oracle stored-procedures plsql
2个回答
2
投票

您的IF条件取决于您没有填充的两个变量。大概这些值来自STUDENT和CLASS表。因此,我认为您需要首先选择相关记录,然后评估IF条件。

类似这样的东西:

create or replace procedure enroll_student2
  (p_stu_ID number,p_class_id number)
as

    l_stu_standing number;
    l_course_standing number;

begin

    select s.stu_standing
    into l_stu_standing
    from student s
    where s.stu_id = p_stu_id;


    select c.course_standing
    into l_course_standing
    from class_sched cs
         inner join course c on c.course_id = cs.course_id
    where c.class_id = p_class_id;

    if l_stu_standing >= l_course_standing then
        insert into enroll (stu_ID, class_id)
        values (p_stu_id, p_class_id); 
    else
        dbms_output.put_line('Requirement not met');
    end if;

end;
/

注意:您尚未发布数据模型,所以我猜了一点:因此,您可能需要修复编译错误。另外,对于可能应包括的明显潜在异常(NO_DATA_FOUND,TOO_MANY_ROWS等),我也没有进行任何错误处理。

您不需要DECLARE,实际上会出现编译错误。匿名块是必需的,但对于命名过程和功能,AS(或IS)关键字表示声明部分的开始。 (对于刚开始使用PL / SQL的人来说,这是一个常见的错误,公平地说,它似乎与触发器的声明不一致。)

最后,请记住,使用DBMS_OUTPUT报告程序失败不是一种可靠的策略。如果用户在关闭SERVEROUTPUT的情况下运行,或者当另一个程序调用此程序时,这也没有好处。


0
投票

请查看帮助中的Ask部分。将其作为问题的模板会大大增加您获得满意答案的机会。确保将所有相关表和示例数据的DDL包括为文本(不是图像)以及该数据的预期结果。但是从所引用的ERD中,以下内容应该起作用。但是,我尚未对其进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.