我创建了一个演示函数来在 PLSQL 中添加两个数字:
create or replace FUNCTION Addition(
x number,
y number
)
RETURN number
AS
result number;
BEGIN
result := x+y;
RETURN result;
END;
/
commit;
现在,我有下表:
Seq Inputl lnput2 Function
--- ------ ------ ----------------
A 1 2 Addition
B 3 4 Subtraction
C 5 6 Addition
D 7 8 Addition
E 9 10 Addition
我必须在我的程序中使用函数,如下所述:
select * bulk collect into data from table order by Seq asc;
for i in 1 .. data.count loop
result(i) := data(i).function(data(i).Input1,data(i).Input2);
end loop;
我使用这种方式时遇到错误。
还有其他方法可以实现吗?
最佳答案
您可以创建一个函数,它接受来自您的表的操作名称,例如“加法”或“减法”:
create or replace function do_the_arith
( operation varchar2
, x number
, y number )
return number
as
begin
return
case upper(operation)
when 'ADDITION' then x + y
when 'MULTIPLICATION' then x * y
when 'SUBTRACTION' then x - y
when 'DIVISION' then x / nullif(y,0) -- to avoid zero divide
when 'POWER' then power(y,y)
when 'LOG' then log(x,y)
end;
end do_the_arith;
/
with t (seq, input1, input2, operation) as
( select 'A', 1, 2, 'Addition' from dual union all
select 'B', 3, 4, 'Multiplication' from dual union all
select 'C', 5, 6, 'Subtraction' from dual union all
select 'D', 7, 8, 'Power' from dual union all
select 'E', 9, 10, 'Log' from dual )
select t.*
, do_the_arith(operation, input1, input2) as result
from t;
SEQ INPUT1 INPUT2 OPERATION RESULT
--- ---------- ---------- -------------- ----------
A 1 2 Addition 3
B 3 4 Multiplication 12
C 5 6 Subtraction -1
D 7 8 Power 16777216
E 9 10 Log 1.04795163
关于oracle - 从 PLSQL 中的表派生函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63021841/