PL/SQL triggers - calculate percentage - oracle

I'm struggling with a problem as I'm VERY new to PL/SQL.
I would like to create a trigger to convert a user supplied percentage value, e.g. 10%.
The column is called deposit in my Booking table. This booking table also has a total cost. I would like to calculate the deposit amount using the supplied percentage and total cost.
So, when a user types in 10% (and all the other data) it will do a calculation using total cost and when the record is inserted, instead of showing 10% it shows the deposit amount.

Although I am not sure how exactly your table looks like this may be what you are looking for:
CREATE OR REPLACE TRIGGER deposit_perc_calc BEFORE
INSERT ON booking FOR EACH ROW
BEGIN
:new.percentage := :new.total_cost*:new.percantage/100;
END;
Maybe you should check the Oracle reference for a guide on coding triggers: http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/triggers.htm#LNPLS020

Related

How to solve "Warning: triggers are created with compilation errors"?

Hi sorry for the inconvenience of posting a bad question. So below is the edit version of the question:
Purpose of this task:
In this task, I am trying to apply the company’s top client is the one who has purchased the most a discount with 15% discount. One of the requirement before creating this trigger is that - should not hardcode the top client since the top client could change when more purchases are made by other clients. I have created a trigger called TOP_CLIENT and edited the code as below:
AFTER UPDATE ON PURCHASE
BEGIN
SELECT PURCHASENO FROM PURCHASE
WHERE (SELECT MAX(AMOUNT) FROM PURCHASE P
JOIN CLIENT C ON P.PURCHASENO = C.CLIENTNO);
UPDATE PURCHASE
SET AMOUNT = (AMOUNT * 0.85)
END;
/
NOTE THAT:
The table CLIENT and PURCHASE are already created and existed in the database.
Shown errors within this code:
enter image description here
Please comment if any of the above doesn't make sense or have any questions related! Thank you!
First, I suggest adding a numeric DiscountRate column to the Client discount and populating it the applicable rate for any clients who get a discount.
Next, I suggest adding a numeric column called the same DiscountRate to the Purchase table.
With those in place, you can update any purchase row AFTER INSERT OR UPDATE only if the DiscountRate has not yet been applied to the purchase or is not equal to the current client discountrate, depending on your business logic;
DROP TRIGGER TOP_DOSCOUNT;
/
CREATE TRIGGER TOP_DOSCOUNT
AFTER INSERT OR UPDATE ON PURCHASE
FOR EACH ROW
WHEN DiscountRate IS NULL
DECLARE dr PURCHASE.DiscountRate%type;
SELECT nvl(C.DiscountRate,0.0) INTO dr FROM CLIENT C
WHERE PurchaseNo = C.ClientNo;
UPDATE PURCHASE
SET Amount = Amount * (1 - dr), DiscountRate = dr;
END;
/
I am unsure if you want to constantly be updating all your prior purchase records with new discount rates. If not, then I suggest this should Only be an insert trigger...but only you know your business logic to be implemented!

Execute Stored Procedure with parameters and insert on one or another table

I'm learning on a Oracle PL/SQL and I'm having a doubt because I don't know if this procedure can be executed.
First, I have 3 tables
TABLE PERSON TABLE CARD TABLE CASH
============ ========== ===========
id_per number number_card number amount number
name varchar2(40) date_expiration date id_per number
payment type varchar(4) ccv number
payment date date payment fees number
id_per number
Well I want to create a stored procedure that ask me the payment type (credit card or cash) and choose, if write card the stored procedure insert data in the tables person and card else insert data in the tables person and cash. My idea it's okay or it's impossible to create that procedure
Adding ontop of Stilgar:
Starting off:
Proc with 3 parameters IN from the person, cash and card tables%rowtypes.
Insert on person (As this happens for either card or cash)
Then a case statement on payment_type which will determine insert on cash or card tables else (Null or nonsense value) return back to calling package/proc.
Then:
Don't know how much or i'm thinking too much of how much else you could do like null handling, validation on your other fields error handling and so forth and rollback / commit on failure/success in the proc's scope. Either get you 'Gotchas' before the proc is called or handle them prior to the inserts in proc.
You can do it!

Oracle - Trigger That When Given One Value Will Fill Another Value in the Same Table?

I'm trying to assist my boyfriend with a project - I have the utmost respect for everyone on here, I hope my lack of knowledge is okay and this question makes sense: He needs a trigger that, when a number is entered in a table, will automatically generate a value in the same table?
For example, if you put $600 under Rent, it would auto-generate 10% of that under 'fee'.
thank you in advance for your assistance!
here is an example :
CREATE OR REPLACE TRIGGER YourTableName_BIU
BEFORE INSERT OR UPDATE OF Rent ON YourTableName
FOR EACH ROW
BEGIN
:new.fee := :new.Rent*10;
END;
Almost there. The problem is with the "* 10". That will give you a fee of 6000 for the 600 rent not the 60 desired. You just need to shift the decimal point; change it to "*.10".

Firebird performance: Update/Select verus Insert/Select last

I have to keep an account balance up to date, a log of changes, and to use it.
It seems to me that the options are to either:
keep it in a single row,
use a trigger to save changes to a separate table
use an select|update to do the update
use a simple select from the table to access the value
The alternative is:
Keep the value in a separate table,
Use Select Last and Insert to effect the update
Use Select Last from the separate table to access the value
Does anyone know which is faster? Is there much in it?
Steve
What you are proposing seems far too complicated...
I would sugest to do a different thing:
I would have two tables with a master-detail relation.
In the detail I would insert rows and its triggers would update the master table
balance (account, amount, ...)
balance_detail (account, amount, ...)
balance_detail_after_insert
begin
update master
set amount = amount + new.amount
where account = new.account;
end
balance_detail_after_update
begin
update master
set amount = amount + new.amount - old.amount
where account = new.account;
end
balance_detail_after_delete
begin
update master
set amount = amount - new.amount
where account = new.account;
end
After any change you should simply close/open the master table to refresh data.

Real Time issues: Oracle Performance tuning (types / indexes / plsql / queries)

I am looking for a real time solution...
Below are my DB columns. I am using Oracle10g. Please help me in defining table types / indexes and tuned PLSQL / query (both) for the updates and insertion
Insert and Update queries are simple but here we need to take care of the performance because my system will execute such 200 times per second.
Let me know... should I use procedures or simple queries? It is requested to write tuned plsql and query with proper DB table types / indexes.
I would really like to see the performance of my system after continuous 200 updates per second
DB table (columns) (I can change the structure if required so please let me know...)
Play ID - ID
Type - Song or Message
Count - Summation of total play
Retries - Summation of total play, if failed.
Duration - Total Duration
Last Updated - Late Updated Date Time
Thanks in advance ... let me know in case of any confusion...
You've not really given a lot of detail about WHAT you are updating etc.
As a basis for you to write your update statements, don't use PL/SQL unless you cannot achieve what you want to do in SQL as the context switching alone will hurt your performance before you even get round to processing any records.
If you are able to create indexes specifically for the update then index the columns that will appear in your update statement's WHERE clause so the records can be found quickly before being updated.
As for inserting, look up the benefits of the /*+ append */ hint for inserting records to see if it will benefit your particular case.
Finally, the table structure you will use will depend on may factors that you haven't even begun to touch on with the details you've supplied, I suggest you either do some research on DB structure or ask your DBA's for a 101 class in it.
Best of luck...
EDIT:
In response to:
Play ID - ID ( here id would be song name like abc.wav something..so may be VARCHAR2, yet not decided..whats your openion...is that fine if primary key is of type VARCHAR2....any suggesstions are most welcome...... ) Type - Song or Message ( varchar2) Count - Summation of total play ( Integer) Retries - Summation of total play, if failed. ( Integer) Duration - Total Duration ( Integer) Last Updated - Late Updated Date Time ( DateTime )
There is nothing wrong with having a PRIMARY KEY as a VARCHAR2 data type (though there is often debate about the value of having a non-specific PK, i.e. a sequence). You must, however, ensure your PK is unique, if you can't guarentee this then it would be worth having a sequence as your PK over having to introduce another columnn to maintain uniqueness.
As for declaring your table columns as INTEGER, they eventually will be resolved to NUMBER anyway so I'd just create the table column as a number (unless you have a very specific reason for creating them as INTEGER).
Finally, the DATETIME column, you only need decare it as a DATE datatype unless you need real precision in your time portion, in which case declare it as a TIMESTAMP datatype.
As for helping you with the structure of the table itself (i.e. which columns you want etc.) then that is not something I can help you with as I know nothing of your reporting requirements, application requirements or audit requirements, company best practice, naming conventions etc. I'm afraid that is something for you to decide for yourself.
For performance though, keep indexes to a minumum (i.e. only index columns that will aid your UPDATE WHERE clause search), only update the minimum data possible and, as suggested before, research the APPEND hint for inserts it may help in your case but you will have to test it for yourself.

Resources