From 395f3a985c84d321da93f17315812f6056b22fa3 Mon Sep 17 00:00:00 2001 From: Kshitij Date: Sat, 9 Nov 2024 00:47:18 +0530 Subject: [PATCH] Added trigger (P9), PL-SQL. --- .../Practical Exam/PL-SQL/P9 - Trigger.md | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Practical/Practical Exam/PL-SQL/P9 - Trigger.md diff --git a/Practical/Practical Exam/PL-SQL/P9 - Trigger.md b/Practical/Practical Exam/PL-SQL/P9 - Trigger.md new file mode 100644 index 0000000..deb56f0 --- /dev/null +++ b/Practical/Practical Exam/PL-SQL/P9 - Trigger.md @@ -0,0 +1,95 @@ +# P9 - Trigger + +**Problem Statement:** + +Trigger: Create a row level trigger for the CUSTOMERS table that would fire INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values. + +--- + +## Creating table: + +```sql +CREATE TABLE Customers( + name VARCHAR(255), + id NUMBER(14), + salary NUMBER(14) +); + +``` + +## Procedure + +```sql +CREATE OR REPLACE TRIGGER P +AFTER INSERT OR UPDATE OR DELETE ON Customers +FOR EACH ROW +DECLARE + diff NUMBER(14); +BEGIN + IF INSERTING THEN + DBMS_OUTPUT.PUT_LINE('New salary with value inserted: ' || :NEW.salary); + ELSIF UPDATING THEN + if :New.salary > :old.salary then diff := :New.salary - :Old.salary; + elsif :New.salary < :old.salary then diff := :Old.salary - :New.salary; + end if; + DBMS_OUTPUT.PUT_LINE('Salary difference: ' || diff); + ELSIF DELETING THEN + DBMS_OUTPUT.PUT_LINE('Salary with value deleted: ' || :OLD.salary); + END IF; +END; +/ + +``` + +## Queries + +1. Insert operation: + +```sql +INSERT INTO Customers VALUES ('Tanmay', 1, 20000); +INSERT INTO Customers VALUES ('Rajesh', 2, 30000); + +``` + +
+ Output + 1 row(s) inserted. + New salary with value inserted: 20000 + 1 row(s) inserted. + New salary with value inserted: 30000 +
+ +2. Update operation: + +```sql +UPDATE Customers SET salary = 10000 WHERE id = 1; +UPDATE Customers SET salary = 35000 WHERE id = 2; + +``` + +
+ Output + 1 row(s) updated. + Salary difference: 10000 + 1 row(s) updated. + Salary difference: 5000 +
+ + +3. Delete operation: + +```sql +DELETE FROM Customers WHERE id = 1; +DELETE FROM Customers WHERE id = 2; + +``` + +
+ Output + 1 row(s) deleted. + Salary with value deleted: 10000 + 1 row(s) deleted. + Salary with value deleted: 35000 +
+ +---