SlideShare a Scribd company logo
1 of 54
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)
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.
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.
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.
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.
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.
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.
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.
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.
•
Syntax for creating Triggers
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;
CREATE OR REPLACE TRIGGER PROD_TRG
BEFORE
INSERT OR UPDATE ON PRODUCT
FOR EACH ROW
BEGIN
:NEW.COST := :NEW.QUANTITY * :NEW.PRICE;
END;
/
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.
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.
Update the price of LAPTOP to 119.85:
UPDATE PRODUCT
SET PRICE = 119.85
WHERE PRODUCT LIKE ‘LAPTOP%’;
•Create a TRIGGER to ensure that the salary
of the employee is not less than 10000.
Write a TRIGGER to ensure that Bus table
does not contain duplicate or null values in Bus_No column.
Create a trigger if ticket no updated is
more than 60 then set its value to 0.
Write a TRIGGER to ensure that
passenger table does not contain
duplicate or null values in PNR_No
column.
By using the %TYPEattribute,
you ensure that the variables have the
same data types as the corresponding
columns in the emptable. This
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
Write a Trigger RESTRICT_TRIG
to restrict all operations on
weekends and non-office hours.
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
Write a PL-SQL Program to Print the salary
changes when the salary is changed.
To Find the Errors in Triggers
SELECT line, position, text
FROM user_errors
WHERE type = 'TRIGGER'
AND name = 'Trigger name';
Confirm the existing triggers:
SELECT trigger_name
FROM all_triggers
WHERE table_name = 'EMP';
Syllabus
CURSORS
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.
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.
Example Explicit cursor
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
• 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.
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.
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
Closing cursor connection
• Syntax:
– CLOSE cursor_name
• Example
– CLOSE s1
• To Deallocate cursor memory
• Syntax:
– DEALLOCATE cursor_name
• Example:
– DEALLOCATE s1
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.
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.
Examples: Creating a table
CREATE TABLE Emp(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int,
Salary int);
Inserting
INSERT INTO Emp (EmpID, Name,Country, Age,
Salary)
VALUES (1, ‘Ravi', 'India',23,30000),
(2, ‘Priya ', 'Australia',21,45000),
(3, 'Naveen', 'Sri lanka',24,40000),
(4, ‘Raju', 'Austria',21,35000),
(5, ‘Anjali', 'Spain',22,25000);
SQL> Select *from Emp;
• 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;
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;
/

More Related Content

Similar to Triggers n Cursors.ppt

Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPTSujayaBiju
 
Exceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant BhabadExceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant Bhabadvasant Bhabad
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 functiondipumaliy
 
plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....Abhiram Vijay
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programmingRushdi Shams
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxvamsiyadav39
 
Basic cursors in oracle
Basic cursors in oracleBasic cursors in oracle
Basic cursors in oracleSuhel Firdus
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 

Similar to Triggers n Cursors.ppt (20)

Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Exceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant BhabadExceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant Bhabad
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
 
plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....
 
4 cursors
4 cursors4 cursors
4 cursors
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Pl sql
Pl sqlPl sql
Pl sql
 
Day 6.pptx
Day 6.pptxDay 6.pptx
Day 6.pptx
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
SQL
SQLSQL
SQL
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Basic cursors in oracle
Basic cursors in oracleBasic cursors in oracle
Basic cursors in oracle
 
Plsql
PlsqlPlsql
Plsql
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 

Recently uploaded

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Recently uploaded (20)

Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

Triggers n Cursors.ppt

  • 1.
  • 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);
  • 52. Inserting INSERT INTO Emp (EmpID, Name,Country, Age, Salary) VALUES (1, ‘Ravi', 'India',23,30000), (2, ‘Priya ', 'Australia',21,45000), (3, 'Naveen', 'Sri lanka',24,40000), (4, ‘Raju', 'Austria',21,35000), (5, ‘Anjali', 'Spain',22,25000); SQL> Select *from Emp;
  • 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; /