簡體   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