我想创建一个plsql过程来计算给定数字的阶乘。
这是步骤:
CREATE OR REPLACE PROCEDURE fact(x IN number, fact OUT number)
IS
BEGIN
while x > 0 loop
fact := x*fact;
x := x-1;
END loop;
END;
/
Warning: Procedure created with compilation errors.
这就是我要调用函数的地方
DECLARE
x number := &x;
fact number := 1;
BEGIN
fact(x,fact);
dbms_output.put_line('Factorial is: '||fact);
END;
这是我得到的错误:
Enter value for x: 5
old 2: x number := &x;
new 2: x number := 5;
fact(x,fact);
*
ERROR at line 5:
ORA-06550: line 5, column 1:
PLS-00221: 'FACT' is not a procedure or is undefined
ORA-06550: line 5, column 1:
PL/SQL: Statement ignored
答案 0 :(得分:3)
您需要像这样转换过程的创建:
SQL> CREATE OR REPLACE PROCEDURE fact(x IN OUT number, fact OUT number) IS
BEGIN
while x > 0 loop
fact := x * nvl(fact, 1);
x := x - 1;
END loop;
END;
/
并致电:
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
x number := &x;
v_fact number := 1;
BEGIN
fact(x, v_fact);
dbms_output.put_line('Factorial is: ' || v_fact);
END;
Factorial is: 120
IN
类型的变量用作分配目标fact
之前将空变量nvl(fact,1)
初始化为fact := 1;
或while x > 0
实际上,对于名为fact OUT number
的过程,您甚至不需要额外的参数fact
,并将其设为本地。因此,您的程序可能被替换为:
SQL> CREATE OR REPLACE PROCEDURE fact(x IN OUT number) IS
fact number := 1;
BEGIN
while x > 0 loop
fact := x * fact;
x := x - 1;
end loop;
x := fact;
END;
/
因此,应调用为:
SQL> DECLARE
x number := &x;
BEGIN
fact(x);
dbms_output.put_line('Factorial is: ' || x);
END;
Factorial is: 120
答案 1 :(得分:1)
您可以考虑将其重写为以下功能:
CREATE OR REPLACE FUNCTION fact(pinX IN INT)
RETURN INT
IS
nResult INT := 1;
BEGIN
FOR i IN 2..pinX LOOP
nResult := i * nResult;
END LOOP;
RETURN nResult;
END FACT;
好运。