PL/SQL 这个 if then 语句有效吗?

PL/SQL Will this if then statement work?

如果p_CreditHour在0到30(含)之间,则系统在屏幕上打印"This student is a Freshmen";如果在 31 到 60 学分之间,打印 "This student is a Sophomore",在 61-90 学分之间,打印 "This student is a Junior";超过 91 个学分,打印 "This student is a Senior."

下面的程序是否反映了前面问题的逻辑?

IF credit <= 30 THEN
     dbms_output.putline ('This student is a Freshmen'.);
END IF;
IF credit <= 60 THEN
     dbms_output.putline ('This student is a
Sophomore.');
END IF;
IF credit <= 90 THEN
     dbms_output.putline ('This student is a Junior.');
END IF;
IF credit > 90 THEN
     dbms_output.putline ('This student is a Senior.');
END IF;

不会,因为 15 小于 30、60 和 90,所以学生将是 Frechman、Sophomore 和 Junior。但是 Oracle 有一个您应该使用的 ELSIF:

IF credit <= 30 THEN
     dbms_output.putline ('This student is a Freshmen'.);
ELSIF credit <= 60 THEN
     dbms_output.putline ('This student is a Sophomore.');
ELSIF credit <= 90 THEN
     dbms_output.putline ('This student is a Junior.');
ELSE
     dbms_output.putline ('This student is a Senior.');
END IF;

或者,还有 CASE 语句。

begin 
  for s in ( select 1 student, 25 credits from dual union all 
             select 2 student, 35 credits from dual union all 
             select 3 student, 65 credits from dual union all 
             select 4 student, 85 credits from dual union all 
             select 5 student, 95 credits from dual 
           ) 
    loop 
      dbms_output.put( 'Student ' || to_char(s.student) || ' is a ');
      case  when s.credits <= 30 then dbms_output.put_line(' Freshman.');
            when s.credits <= 60 then dbms_output.put_line(' Sophomore.');
            when s.credits <= 90 then dbms_output.put_line(' Junior.');
            else  dbms_output.put_line(' Senior.');
      end case;
    end loop; 
end;

或者您可以使用 ADD 语句。

IF credit <= 30 THEN
 dbms_output.putline ('This student is a Freshmen'.);
ElSIF credit <= 60 AND credit > 30 THEN
 dbms_output.putline ('This student is a Sophomore.');
ELSIF credit <= 90 AND credit > 60 THEN
 dbms_output.putline ('This student is a Junior.');
ELSE
 dbms_output.putline ('This student is a Senior.');
END IF;