for for循环中有两个参数和多个计算输出

时间:2018-04-08 19:50:59

标签: plsql foreach parameters

好的,必须有更好的方法......给定常数:

Path

对于输入参数(n,单位),单位为(天,小时,分钟,秒,秒), 转换为其他三个并显示结果。

以下匿名块编译,运行并解决问题。有没有办法避免键入所有BEGIN ... END四次,每对参数一次?

create or replace PACKAGE time_conversion_cons AS 
  c_day_to_hr    CONSTANT NUMBER := 24; 
  c_day_to_min   CONSTANT NUMBER := 1440; 
  c_day_to_sec   CONSTANT NUMBER := 86400;
  c_hr_to_day    CONSTANT NUMBER := .0417; 
  c_hr_to_min    CONSTANT NUMBER := 60; 
  c_hr_to_sec    CONSTANT NUMBER := 3600;
  c_min_to_day   CONSTANT NUMBER := .000694; 
  c_min_to_hr    CONSTANT NUMBER := .0167; 
  c_min_to_sec   CONSTANT NUMBER := 60;
  c_sec_to_day   CONSTANT NUMBER := .0001157; 
  c_sec_to_hr    CONSTANT NUMBER := .000478; 
  c_sec_to_min   CONSTANT NUMBER := .167;
END time_conversion_cons; -- this package spec compiles and runs fine.

1 个答案:

答案 0 :(得分:1)

SQL>
SQL> create or replace PACKAGE time_conversion_cons AS
  2    type  dim1 is table of number index by varchar2(10);
  3    type  dim2 is table of dim1   index by varchar2(10);
  4    l_matrix dim2;
  5
  6    l_tags sys.odcivarchar2list := sys.odcivarchar2list('day','hr','min','sec');
  7  end;
  8  /

Package created.

SQL>
SQL> create or replace PACKAGE body time_conversion_cons AS
  2  begin
  3    l_matrix('day')('hr'):= 24;
  4    l_matrix('day')('min'):= 1440;
  5    l_matrix('day')('sec'):= 86400;
  6    l_matrix('hr')('day'):= .0417;
  7    l_matrix('hr')('min'):= 60;
  8    l_matrix('hr')('sec'):= 3600;
  9    l_matrix('min')('day'):= .000694;
 10    l_matrix('min')('hr'):= .0167;
 11    l_matrix('min')('sec'):= 60;
 12    l_matrix('sec')('day'):= .0001157;
 13    l_matrix('sec')('hr'):= .000478;
 14    l_matrix('sec')('min'):= .167;
 15  END;
 16  /

Package body created.

SQL>
SQL>
SQL> set serverout on
SQL> DECLARE
  2    v_n1 NUMBER := 2.5;
  3    v_u1 VARCHAR2(10) := 'day';
  4  BEGIN
  5    for i in 1 .. time_conversion_cons.l_tags.count loop
  6      if time_conversion_cons.l_tags(i) != v_u1 then
  7         dbms_output.put_line(v_u1||' to '||time_conversion_cons.l_tags(i));
  8         dbms_output.put_line(v_n1*time_conversion_cons.l_matrix(v_u1)(time_conversion_cons.l_tags(i)));
  9      end if;
 10    end loop;
 11  END;
 12  /
day to hr
60
day to min
3600
day to sec
216000

PL/SQL procedure successfully completed.

SQL>
SQL>