繁体   English   中英

如何在 Oracle PL/SQL 中执行存储的 function

[英]How to execute stored function in Oracle PL/SQL

我想执行这个存储的function,并在表t中插入数据我试图找到解决方案,但没有成功

CREATE TABLE t (id number
              , name varchar2(32)
              , time date);

CREATE OR REPLACE PACKAGE t_api AS
    FUNCTION func_ins (
        p_row IN t%rowtype
    ) RETURN t.id%TYPE;
END t_api;
/

CREATE OR REPLACE PACKAGE BODY t_api AS
FUNCTION func_ins (
    p_row IN t%rowtype
) RETURN t.id%TYPE 
IS
    l_id t.id%TYPE;
BEGIN
    INSERT INTO t VALUES p_row RETURNING id INTO l_id;    
    RETURN l_id;
END func_ins;
END t_api;
/


declare
p_row t%rowtype;
begin
p_row.id := 1;
p_row.name := 'name';
p_row.time := sysdate;
t_api.func_ins(p_row);
end;
/

我有

PLS-00221

提前致谢

它工作得很好,但是我不推荐这种设计,因为它不是在 function 中执行 DML 的好习惯。 而是创建一个过程而不是 function 并使用 out 参数检索 Id。

当表为空时,匿名块测试 function。您为 %ROWTYPE 变量分配值并插入。

  declare 
    t_row t%rowtype;
    x t.id%type;
    begin

    t_row.id := 2;
    t_row.name := 'Test2';
    t_row.time := sysdate;

     x :=  t_api.func_ins(t_row);

     dbms_output.put_line('x '||x);

    end;

Output 是

 x 2

使用过程修改代码以达到相同的结果如下,

CREATE OR REPLACE PACKAGE t_api AS
    FUNCTION func_ins (
        p_row IN t%rowtype
    ) RETURN t.id%TYPE;
  PROCEDURE   proc_ins (
    p_row IN t%rowtype,
    l_id out t.id%TYPE
); 
END t_api;
/

CREATE OR REPLACE PACKAGE BODY t_api AS
FUNCTION func_ins (
    p_row IN t%rowtype
) RETURN t.id%TYPE 
IS
    l_id t.id%TYPE;
BEGIN
    INSERT INTO t VALUES p_row RETURNING id INTO l_id;    
    RETURN l_id;
END func_ins;
PROCEDURE proc_ins (
    p_row IN t%rowtype,
    l_id out t.id%TYPE
) 
IS

BEGIN
    INSERT INTO t VALUES p_row RETURNING id INTO l_id;    

END proc_ins;
END t_api;
/

匿名块来测试程序,

declare 
t_row t%rowtype;
x t.id%type;
begin


t_row.id := 3;
t_row.name := 'Test3';
t_row.time := sysdate;

 t_api.proc_ins(t_row,x);
 dbms_output.put_line('x '||x);


end;

Output 是

× 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM