Control Structures and Loop Structures in PL/SQL Programming

control structure

if

①if condition then expression end if;
example:

begin
 if 1= 1 then dbms_output.put_line('yes'); end if;
end;
/

② if condition 1 then expression 1
elsif condition 2 then expression 2

elsif condition n then expression n
else expression end if;

Similar to the combination of if and elseif, note that here is the elsif
example:

declare
  v_sal emp.sal%type;
  v_result varchar2(8);
begin
  select sal into v_sal from emp where empno = &empno;
  if v_sal < 1500 then v_result := '低工资' ;
  elsif v_sal < 3000 then v_result := '正常工资';
  else v_result := '高工资'; end if;
  dbms_output.put_line(v_result);
exception
  when no_data_found then
     dbms_output.put_line('员工不存在');
end;
/

case

① case expression
when value 1 then expression 1
when value 2 then expression 2

else expression
end case;
this usage is similar to the switch structure (switch) and no example

② case
when condition 1 then expression 1
when condition 2 then expression 2

when condition n then expression n
else expression
end case;

example:

declare
  v_sal emp.sal%type;
  v_result varchar2(8);

begin
  select sal into v_sal from emp where empno = &empno;
  case 
  when v_sal < 1500 then v_result := '低工资';
  when v_sal > 1500 and v_sal <3000 then v_result := '一般工资';
  else v_result := '高工资'; end case;
  dbms_output.put_line(v_result);
exception
  when no_data_found then
     dbms_output.put_line('员工不存在');
end;
/

Note: The statement in the expression that should be added with a semicolon must be added! ! !


loop structure

loop, while, for. In the future, the sum of 1 to 100 will be used as an example.

①loop:

declare
  v_sum int:= 0;
  v_i int:= 1;
begin
  loop
    v_sum := v_sum + v_i;
    v_i := v_i +1;
    exit when v_i = 101;
  end loop;
dbms_output.put_line(v_sum);
end;
/

Exit when is followed by the condition to exit the loop

②while

declare
  v_sum int:= 0;
  v_i int:= 1;
begin
  while v_i < 101 loop
    v_sum := v_sum + v_i;
    v_i := v_i +1;
  end loop;
dbms_output.put_line(v_sum);
end;
/

③for

declare
  v_sum int:= 0;
begin
  for v_i in 1..100 loop
    v_sum := v_sum + v_i;
  end loop;
dbms_output.put_line(v_sum);
end;
/

The for loop is suitable for cases where the number of loops is determined, while while and loop are suitable for cases where the number of loops is not determined. (It's a cliché~~)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326693220&siteId=291194637