Oracle PL/SQL基础 选择(IF CASE) 、 循环(LOOP WHILE FOR)


一、PL/SQL的控制结构,包括选择结构、循环结构和跳转结构

rlwrap - 解决Linux下SQLPLUS退格、上翻键乱码问题

SQLPLUS spool 到动态日志文件名

Oracle SQLPLUS提示符设置

通过设置SQLPLUS ARRAYSIZE(行预取)加快SQL返回速度
 
1、选择结构
 
(1)IF语句

IF condition1 THEN  statement1 ;
[ ELSIF condition2 THEN statement2 ; ]
...
[ ELSE else_statements ; ]
END IF;

Attention:PL/SQL的逻辑运算结果有 TRUE 、 FALSE 、NULL 三种情况,所以在进行条件选择判断时,要考虑条件结果为NULL的情况。

Example:

create or replace procedure detector_plsql_if(
      v_control_type in varchar2)
as
    v_pre_print varchar2(100) := 'value of parameter [in] v_control_type';
begin

    if v_control_type = 'if' then
      dbms_output.put_line(v_pre_print || ' (if) :' || v_control_type);
    elsif v_control_type = 'case' then
      dbms_output.put_line(v_pre_print || ' (case) :' || v_control_type);
    elsif v_control_type is null then
      dbms_output.put_line(v_pre_print || ' (null) :' || v_control_type);
    else
      dbms_output.put_line(v_pre_print || ' :' || v_control_type);
    end if;

end detector_plsql_if;

(2)、CASE 语句

CASE语句有两种形式:一种只进行等值比较,另一种可以进行多各种条件比较。

A、只进行等值比较

CASE test_value
 WHEN value1 THEN statement1;
[ WHEN value2 THEN statement2; ]
...
[ ELSE else_statement ; ]
END CASE;

Example:

create or replace procedure detector_plsql_case(
  v_control_type in varchar2)
is
  v_pre_print varchar2(100) := 'value of parameter [in] v_control_type';
begin

    case v_control_type
      when 'if' then
          dbms_output.put_line(v_pre_print || ' (if) :' || v_control_type);
      when 'case' then
          dbms_output.put_line(v_pre_print || ' (case) :' || v_control_type);
      else
          dbms_output.put_line(v_pre_print || ' :' || v_control_type);
    end case;

end detector_plsql_case;

B、进行多种条件的比较

CASE
        WHEN condition1 THEN statement1 ;
        [ WHEN condition2 THEN statement2; ]
        ...
        [ ELSE else_statements ; ]
END CASE;

CASE语句对每一个WHEN条件进行判断,当条件为真时,执行其后面的语句;如果所有条件都不为真,则执行ELSE后的语句。

Attention:在CASE语句中,当第一个WHEN条件为真时,执行其后的操作,操作完成后结束CASE语句,其它的WHEN条件不再判断,其后的操作也不执行。

Example:

create or replace procedure detector_plsql_case2(
 v_control_type in varchar2)
as
  v_pre_print varchar2(100) := 'value of parameter [in] v_control_type';
begin

  case
    when v_control_type = 'if' then
        dbms_output.put_line(v_pre_print || ' (if) :' || v_control_type);
    when v_control_type = 'case' then
          dbms_output.put_line(v_pre_print || ' (case) :' || v_control_type);
    when v_control_type is null then
          dbms_output.put_line(v_pre_print || ' (null) :' || v_control_type);
    else
          dbms_output.put_line(v_pre_print || ' :' || v_control_type);     
  end case;

end detector_plsql_case2;

更多详情见请继续阅读下一页的精彩内容:

  • 1
  • 2
  • 下一页

相关内容