2013-05-31 39 views
0

我已经构建了此函数来打印所有项目的列表以及每个项目的总承诺量。我需要格式化输出以显示$符号,逗号和值的两位小数。从SQL语句中用to_char调用PL/SQL函数

到目前为止,我可以得到结果,但没有格式。我在函数中包含了to_char

当我调用它,我收到此错误:

ORA-06502: PL/SQL: numeric or value error: character to number conversion error 
ORA-06512: at "SYSTEM.DD_PROJECT_SF", line 19 
06502. 00000 - "PL/SQL: numeric or value error%s" 
*Cause:  

*操作:

这里是我的功能:

create or replace function DD_PROJECT_SF (

project_id dd_project.idproj%type) 

return number is 

pledge_amount dd_pledge.pledgeamt%type; 
project_name dd_project.projname%type; 
projid  dd_pledge.idproj%type; 

begin 

select idproj, projname into projid, project_name from dd_project 

where idproj = project_id; 

select to_char(sum(pledgeamt), '$9,990.99') into pledge_amount from dd_pledge 
where idproj = project_id; 

if (pledge_amount = 0) then 
return 0; 
else 
return pledge_amount; 
end if; 

return pledge_amount; 

end DD_PROJECT_SF; 

这是调用SQL语句:

select idproj, projname, DD_PROJECT_SF(idproj) from dd_project; 

我该如何解决这个问题?

+0

“dd_pledge.pledgeamt”的类型是什么? –

+0

@JoachimIsaksson它是数字(8,2) – user2396035

回答

3

首先,你要返回一个数字并选择一个varchar为一个数字变量。你需要所有的数据类型都是一样的。当你想要返回一个字符时,可能会更容易将一个数字选择到一个数字中,然后在返回时将该变量转换为一个字符。

其次,这里有很多不必要的代码。它可以简化为:

create or replace function DD_PROJECT_SF (
    Pproject_id dd_project.idproj%type 
    ) return varchar2 is 

    -- As you're summing you don-t know 
    -- whether the sum will fit in the same 
    -- data type so extend to the maximum 
    pledge_amount number; 

begin 

    -- select a number 
    select sum(pledgeamt) into pledge_amount 
    from dd_pledge 
    where idproj = Pproject_id; 

    -- return a character 
    return to_char(pledge_amount, '$9,990.99'); 

end DD_PROJECT_SF; 

作为一个侧面说明,作为你总结你怎么知道的最高金额将低于$ 10,000?您可能想要扩展此以考虑更大的数字。

最后,这是一种可以在SQL语句而非PL/SQL中轻松完成的事情。考虑如果可能的话使用一个。


您已经评价说:

... I used the if statement here as I want the function to show me zero instead of null where the total is 0. so how may I include it in your code.I tried to but not succeeded

这个函数总是返回0,如果承诺的总和为0。它将返回NULL,如果有涉及到这IDPROJ中没有数据桌子。

就个人而言,如果是这样的话,我不会掩饰你没有数据的事实。 NULL和0在逻辑上是不同的;如果你这样做,你会失去这种区别。尽管如此,如果你总是想返回一个0,如果你没有数据,那么你可以使用NVL()来这样做。将您的退货声明更改为以下内容:

return to_char(nvl(pledge_amount, 0), '$9,990.99'); 
+0

以及我在这里使用if语句,因为我希望函数向我显示零而不是null,因此总数为0.因此,如何将它包含在您的代码中。我尝试过但未成功 – user2396035

+0

我已更新我的answer @ user2396035,因为它不适合发表评论。 – Ben

+0

完美运行我坚持了几天...感谢很多家伙.... – user2396035