Triggers in PL/SQL are blocks of code that are automatically executed in response to certain events or actions on a database table, such as INSERT, UPDATE or DELETE operations. There are different types of triggers including row-level triggers that fire for each row affected, statement-level triggers that fire once per SQL statement, and timing triggers that fire before or after the triggering statement. Triggers are useful for maintaining complex constraints, recording changes made to tables, and enforcing referential integrity. A trigger contains a triggering event, an optional trigger restriction, and the trigger action to be executed.
2. Triggers in PL/SQL
• Triggers in oracle are blocks of PL/SQL code
which oracle engine can execute automatically
based on some action or event.
• These events can be:
– DDL statements (CREATE, ALTER, DROP,
TRUNCATE)
– DML statements (INSERT, SELECT, UPDATE,
DELETE)
– Database operation like connecting or
disconnecting to oracle (LOGON, LOGOFF,
SHUTDOWN)
3. Triggers….
• Triggers are automatically and repeatedly
called upon by oracle engine on satisfying
certain condition.
• Triggers can be activated or deactivated
depending on the requirements.
• If triggers are activated then they are executed
implicitly by oracle engine and if triggers are
deactivated then they are executed explicitly
by oracle engine.
4. PL/SQL: Uses of Triggers
• Here we have mentioned a few use cases where
using triggers proves very helpful:
• Maintaining complex constraints which is either
impossible or very difficult via normal constraint(like
primary, foreign, unique etc) applying technique.
• Recording the changes made on the table.
• Automatically generating primary key values.
• Prevent invalid transactions to occur.
• Granting authorization and providing security to
database.
• Enforcing referential integrity.
5. PL/SQL: Parts of a Trigger
• Whenever a trigger is created, it contains the
following three sequential parts:
• Triggering Event or Statement: The
statements due to which a trigger occurs is
called triggering event or statement. Such
statements can be DDL statements, DML
statements or any database operation,
executing which gives rise to a trigger.
6. PL/SQL: Parts of a Trigger
• Trigger Restriction: The condition or any
limitation applied on the trigger is called
trigger restriction. Thus, if such a condition
is TRUE then trigger occurs otherwise it does
not occur.
• Trigger Action: The body containing the
executable statements that is to be executed
when trigger occurs that is with the execution
of Triggering statement and upon evaluation
of Trigger restriction as True is called Trigger
Action.
7. PL/SQL: Types of Triggers
• The above diagram clearly indicated that
Triggers can be classified into three categories:
– Level Triggers
– Event Triggers
– Timing Triggers
• which are further divided into different parts.
8. Level Triggers
• There are 2 different types of level triggers,
they are:
• ROW LEVEL TRIGGERS
– It fires for every record that got affected with the
execution of DML statements like INSERT, UPDATE,
DELETE etc.
– It always use a FOR EACH ROW clause in a
triggering statement.
• STATEMENT LEVEL TRIGGERS
– It fires once for each statement that is executed.
9. Event Triggers
• There are 3 different types of event triggers, they
are:
• DDL EVENT TRIGGER
– It fires with the execution of every DDL statement(CREATE,
ALTER, DROP, TRUNCATE).
• DML EVENT TRIGGER
– It fires with the execution of every DML statement(INSERT,
UPDATE, DELETE).
• DATABASE EVENT TRIGGER
– It fires with the execution of every database operation
which can be LOGON, LOGOFF, SHUTDOWN,
SERVERERROR etc.
10. Timing Triggers
• There are 2 different types of timing triggers,
they are:
• BEFORE TRIGGER
– It fires before executing DML statement.
– Triggering statement may or may not executed
depending upon the before condition block.
• AFTER TRIGGER
– It fires after executing DML statement.
•
12. Trigger example
CREATE TABLE PRODUCT (PNAME
VARCHAR2(16), QUANTITY NUMBER,
PRICE NUMBER, COST NUMBER);
INSERT INTO PRODUCT(PNAME,
QUANTITY, PRICE) VALUES (‘LAPTOP’, 4,
90.00);
SELECT * FROM PRODUCT;
13. CREATE OR REPLACE TRIGGER PROD_TRG
BEFORE
INSERT OR UPDATE ON PRODUCT
FOR EACH ROW
BEGIN
:NEW.COST := :NEW.QUANTITY * :NEW.PRICE;
END;
/
14. The trigger PROD _TRG will fire once for each row affected
by the insert or update operations.
It will fire before the row is inserted or updated and the new
value of the Cost column will be calculated as the Quantity
times Price.
15. Check if it works.
Insert another row into PRODUCT:
INSERT INTO PRODUCT(PRODUCT, QUANTITY,
PRICE) VALUES (MONITOR’, 5, 105.50);
SELECT * FROM PRODUCT;
Notice the value in the Cost column has been updated
automatically for MONITOR but not for LAPTOP.
16. Update the price of LAPTOP to 119.85:
UPDATE PRODUCT
SET PRICE = 119.85
WHERE PRODUCT LIKE ‘LAPTOP%’;
17. •Create a TRIGGER to ensure that the salary
of the employee is not less than 10000.
18.
19. Write a TRIGGER to ensure that Bus table
does not contain duplicate or null values in Bus_No column.
20.
21. Create a trigger if ticket no updated is
more than 60 then set its value to 0.
22.
23.
24.
25. Write a TRIGGER to ensure that
passenger table does not contain
duplicate or null values in PNR_No
column.
26.
27.
28. By using the %TYPEattribute,
you ensure that the variables have the
same data types as the corresponding
columns in the emptable. This
29. Write a PL-SQL Program to create a trigger to backup a
row which is delete from the one table and inserted in the
another table
30.
31. Write a Trigger RESTRICT_TRIG
to restrict all operations on
weekends and non-office hours.
32.
33. Write a trigger to do the following:
if the ticket is booked in advance of more
than 60 days, reject it.
I.e, date of journey must not greater than
60 days from reservation date
34.
35.
36. Write a PL-SQL Program to Print the salary
changes when the salary is changed.
37. To Find the Errors in Triggers
SELECT line, position, text
FROM user_errors
WHERE type = 'TRIGGER'
AND name = 'Trigger name';
38. Confirm the existing triggers:
SELECT trigger_name
FROM all_triggers
WHERE table_name = 'EMP';
41. CURSORS
• Cursor is a Temporary Memory or Temporary
Work Station. It is Allocated
by Database Server at the Time of
Performing DML(Data Manipulation Language)
operations on the Table by the User. Cursors
are used to store Database Tables.
• There are 2 types of Cursors: Implicit Cursors,
and Explicit Cursors.
42. TYPES OF CURSORS
• Implicit Cursors: Implicit Cursors are also
known as Default Cursors of SQL SERVER.
These Cursors are allocated by SQL SERVER
when the user performs DML operations.
• Explicit Cursors: Explicit Cursors are Created
by Users whenever the user requires them.
Explicit Cursors are used for Fetching data
from Table in Row-By-Row Manner.
44. How To Create Explicit Cursor?
• Step 1:
• Declare Cursor Object
• Syntax:
DECLARE cursor_name CURSOR is SELECT *
FROM table_name;
Example:
DECLARE s1 CURSOR FOR SELECT * FROM
studDetails
45. • Step 2: Open cursor connection.
• Syntax:
– OPEN cursor_connection
• Example:
– OPEN s1
• Fetching the cursor:
– FETCH c_customers INTO c_id, c_name, c_addr;
• Closing the cursor:
– Close c_customers.
46. Fetching data from Cursor
• Fetch Data from the Cursor There is a total of
6 methods to access data from the cursor.
• FIRST is used to fetch only the first row from the cursor table.
• LAST is used to fetch only the last row from the cursor table.
• NEXT is used to fetch data in a forward direction from the
cursor table.
• PRIOR is used to fetch data in a backward direction from the
cursor table.
• ABSOLUTE n is used to fetch the exact nth row from the cursor
table.
• RELATIVE n is used to fetch the data in an incremental way as
well as a decremental way.
47. Fetching…..
• Syntax:
– FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE
n/RELATIVE n FROM cursor_name
• Example:
• FETCH FIRST FROM s1
• FETCH LAST FROM s1
• FETCH NEXT FROM s1
• FETCH PRIOR FROM s1
• FETCH ABSOLUTE 7 FROM s1
• FETCH RELATIVE -2 FROM s1
48. Closing cursor connection
• Syntax:
– CLOSE cursor_name
• Example
– CLOSE s1
• To Deallocate cursor memory
• Syntax:
– DEALLOCATE cursor_name
• Example:
– DEALLOCATE s1
49. How To Create an Implicit Cursor?
• An implicit cursor is a cursor that is
automatically created by PL/SQL when you
execute a SQL statement. You don’t need to
declare or open an implicit cursor explicitly.
Instead, PL/SQL manages the cursor for you
behind the scenes.
50. Cursor Attributes
• This SQL cursor has several useful attributes.
• %FOUND is true if the most recent SQL operation
affected at least one row.
• %NOTFOUND is true if it didn’t affect any rows.
• %ROWCOUNT is returns the number of rows
affected.
• %ISOPEN checks if the cursor is open.
51. Examples: Creating a table
CREATE TABLE Emp(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int,
Salary int);
53. • This program updates a table by increasing the salary of each
employee by 1500. After the update, the SQL%ROWCOUNT
attribute is used to find out how many rows were affected by
the operation.
DECLARE
total_rows number(2);
BEGIN
UPDATE EMP
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected
');
END IF;
54. Explicit Cursor
DECLARE
c_id customers.customerid%type;
c_name customers.customername%type;
ct_name customers.contactname%type;
CURSOR c_customers is
SELECT customerid, customername, contactname FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, ct_name;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || ct_name);
END LOOP;
CLOSE c_customers;
END;
/