程序调用函数时出错

时间:2016-10-22 09:54:41

标签: oracle plsql

我编写了函数,并在下面调用过程。两种编码都可以执行,但是当我执行ProdDetails(10010)时,它会显示错误。谁能知道什么是问题?

       create or replace function ProdCheck(
    f_product_id in number)
    return varchar IS
    f_product_name varchar(30);
    f_product_price number;
    begin
     select product_name, price into f_product_name, f_product_price 
     from product
     where product_id = f_product_id;
    return f_product_name;
    end;

create or replace procedure ProdDetails(
sp_product_id in number
)IS
f_product_id number;
sp_name varchar(30);
sp_price number;

begin
f_product_id := ProdCheck(sp_product_id);
if f_product_id > 0 then
dbms_output.put_line('Product Name : '||sp_name);
dbms_output.put_line('Product Price : '||sp_price);
else
dbms_output.put_line('Product not in the database!');
end if;
end;

enter image description here

1 个答案:

答案 0 :(得分:1)

您的功能prodcheck需要product_id并返回product_name。然后在调用函数的过程中,为函数a product_id提供函数(到目前为止一切正常),然后将函数的返回值(即产品名称)赋给变量f_product_id ,您声明为number。显然这是行不通的。事实上,功能和程序在语法上都是正确的;只有当你把它们放在一起时才会失败,并且只有在运行时才会因为Oracle没有严格执行数据类型(如果产品名称为'1000',那么函数可能会执行正常 - 并产生垃圾结果,因为它会解释这个产品名称代替产品ID。

您在函数中查询表以检查产品ID是否有效,并返回名称。在该过程中,您可以将函数的返回值分配给sp_name。该函数不会返回价格(它不能 - 函数不能返回多个值),因此您无法在过程中显示价格。你可以在程序中再次查询表,但这看起来很无趣;将所有内容组合到一个程序中会更好。 (您可能根本不需要检查 - 如果表中不存在产品ID,您将获得“无行”异常,您可以使用它而不是prodcheck。)