TABLE DESC:

Customer (Custid, Custname, Addr, phno,panno)
Loan (Loanid, Amount, Interest, Custid)
Account (Accd, Accbal, Custid)

QUERY IS:

Create a Trigger which checks whether the Accbal is atleast 25% of amount to be inserted in Loan.

MY TRIGGER CODE IS:

create or replace trigger claim before
insert on loan for each row
declare
  ex exception;
  bal number;
begin
  select accbal into bal from account where :new.custid=account.custid;
  if(bal < 0.25*:new.amount)then
    raise ex;
  end if;
EXCEPTION
 when ex then
  raise_application_error(-20001,'Balance is not sufficient');
end;
/

My trigger was created. But while inserting values in loan (intending to get the error) the error was not raised. Any Corrections to be made in my code?

Suppose these are the values:

LOANID     AMOUNT   INTEREST CUSTID
------- ---------- ---------- ------
  1001     100000       2000 C01
  1002     200000    4081.41 C02
  1003      50000       1000 C03

  ACCD     ACCBAL CUSTID
---------- ------ ------
  2001       5000 C01
  2002     105000 C02
  2003      24000 C03

If I am going to insert this:

insert into loan values(1004,100000,2000,'C02');

it must raise an error as the quarter of the new amount "100000" =25000 [0.25*:new.amount] is less than accbal i.e. 105000 for the corresponding custid "C02".

But it is not happening with this trigger code. Instead it directly inserts the values in the table.

有帮助吗?

解决方案

You're inserting a new load with amount 100000, for a customer whose account balance is 105000. The rule is to check whether the balance is at least 25% of the amount of the loan. 25% of your loan value is 25000, and the balance is much higher than that.

For your trigger to raise the exception the loan amount would need to be more than four times the balance:

insert into loan values (1004, 100000, 2000, 'C02');

1 rows inserted.

insert into loan values (1005, (100005 * 4), 2000, 'C02');

1 rows inserted.

insert into xloan values (1006, (105000 * 4) + 1, 2000, 'C02')

Error report -
SQL Error: ORA-20001: Balance is not sufficient
ORA-06512: at "MYSCHEMA.CLAIM", line 11
ORA-04088: error during execution of trigger 'MYSCHEMA.CLAIM'

So you just have the logic the wrong way round when you're creating the data and insert statement.

You can simplify the trigger a bit, incidentally, as you don't need to raise and catch the ex exception, you can just raise your own error as soon as you spot the problem:

create or replace trigger claim
before insert on loan
for each row
declare
  bal number;
begin
  select accbal into bal from account where :new.custid=account.custid;
  if bal < (0.25*:new.amount) then
    raise_application_error(-20001,'Balance is not sufficient');
  end if;
end;
/
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top