2012-02-21 17 views
0

我已经通过Internet搜索了一些资源,为我提供了一个如何调用我在PL/SQL中的触发器中创建的函数的示例。在pl/sql的触发器中调用函数

我做了一个名为get_balance功能,看起来像这样:

create or replace function get_balance(p_custno in number) 
return number 
as 
v_balance account.balance%type; 
begin 
select balance 
into v_balance 
from account 
where custno = p_custno; 
return v_balance; 
end; 
/

现在我想调用此函数从触发器内取款前检查的平衡。我试着做如下,但我认为这是完全错误的:

create or replace trigger bifer_withdrawal 
before insert on withdrawal 
for each row 
begin 
if get_balance(p_custno) <= amount then 
raise_application_error(-20001, 'Not enough money in account!'); 
end if; 
end; 
/

可能有人请提供一个新手用的如何从一个触发器中调用一个函数的例子吗?

+0

你正在做正确的唯一....任何错误你有编译这个吗? – 2012-02-21 11:08:25

+0

环境交易? – 2012-02-21 11:09:28

+0

它编译,但我收到警告。 – Posidon 2012-02-21 11:25:59

回答

2

你需要指定p_custno值我使用了默认的NEW别名但见here触发信息,还勒Nyffenegger的有NEWOLD使用的good explanation

create or replace 
trigger bifer_withdrawal 
before insert on withdrawal 
for each row 
begin 
    if get_balance(:NEW.custno) <= amount 
    then 
     raise_application_error(-20001, 'Not enough money in account!'); 
    end if; 
end; 
/

您需要指定什么AMOUNT也是。如果它是一个变量,然后宣布它的FOR EACH ROWBEGIN语句之间:

例如为:

create or replace 
trigger bifer_withdrawal 
before insert on withdrawal 
for each row 
declare 
    c_amount CONSTANT account.balance%TYPE := 5000; -- Whatever limit you need 
begin 
    if get_balance(:NEW.custno) <= c_amount 
    then 
     raise_application_error(-20001, 'Not enough money in account!'); 
    end if; 
end; 
/

你应该问问自己,你需要调用函数?
您可以轻松地将光标封装到触发器中并保存函数调用。
您的答案将取决于您是否想要在其他地方重复使用该功能等问题。
我不是主张一种方式,而是考虑其他方面。

希望它可以帮助...

编辑:下面的两点意见后,如果AMOUNT是在表中的列WITHDRAWAL则:

create or replace 
trigger bifer_withdrawal 
before insert on withdrawal 
for each row 
begin 
    if get_balance(:NEW.custno) <= :NEW.amount 
    then 
     raise_application_error(-20001, 'Not enough money in account!'); 
    end if; 
end; 
/
+0

我想他想给:NEW.amount代替5000(您的第二个查询).. – 2012-02-21 12:47:01

+0

感谢您的帮助!我应该更准确地解释我的问题,“金额”是表格提取中的一列。 – Posidon 2012-02-21 13:18:53

+0

由于上述评论而编辑的答案... – Ollie 2012-02-21 13:24:52