oracle - 从 PLSQL 中的表派生函数

标签 oracle function stored-procedures plsql

我创建了一个演示函数来在 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/

相关文章:

c++ - 在 C++ 中定义两个具有相同签名的函数

sql - 我的 SQL Server 存储过程中的 BIT 值类型存在语法问题

mysql - 使用 Symfony 1.4 和 Doctrine 从 SQL 过程调用获取下一组结果

java - 是否可以删除在 Windows 8.1 中安装 java 8u60 时创建的文件夹路径?

python - 从 Python 查询 Windows Server 2008 上的 Oracle 数据库

sql - 从sql plus中的字符串中删除第一个字符

java - 偏移量 1 处的格式错误的函数或过程转义语法

sql - 如何将数据类型 CLOB 更改为 VARCHAR2(sql)

javascript - 从 JavaScript 中的多个函数返回结果

JavaScript : use string to invoke function