SlideShare a Scribd company logo
1 of 5
AIM:
          TRIGGER AND CURSOR PROGRAM USING SQL


                             INTRODUCTION:
In SQL procedures, a cursor make it possible to define a result set (a set of data
     rows) and perform complex logic on a row by row basis. By using the same
mechanics, an SQL procedure can also define a result set and return it directly to
            the caller of the SQL procedure or to a client application.



A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only
   reference one row at a time, but can move to other rows of the result set as
                                      needed.



         To use cursors in SQL procedures, you need to do the following:

                   1)Declare a cursor that defines a result set.

                  2)Open the cursor to establish the result set.

3)Fetch the data into local variables as needed from the cursor, one row at a time.

                          4)Close the cursor when done.



     The SQL CREATE TRIGGER statement provides a way for the database
  management system to actively control, monitor, and manage a group of tables
whenever an insert, update, or delete operation is performed. The statements
  specified in the SQL trigger are executed each time an SQL insert, update, or
delete operation is performed. An SQL trigger may call stored procedures or user-
 defined functions to perform additional processing when the trigger is executed.




                                  CURSOR PROGRAM:

 The following PROGRAM uses a cursor to select the five highest paid employees
                                  from the emp table.



                                        Input Table

                   SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;




                                  ENAME          EMPNO        SAL

                                    ---------- --------- --------

                                   KING           7839     5000

                                   SCOTT          7788      3000

                                   FORD           7902      3000

                                   JONES           7566     2975

                                   BLAKE          7698      2850

                                   CLARK          7782      2450

                                   ALLEN          7499      1600

                                   TURNER          7844      1500

                                   MILLER          7934     1300

                                   WARD            7521     1250

                                  MARTIN           7654      1250

                                   ADAMS           7876      1100
JAMES           7900      950

               SMITH           7369      800

                      PL/SQL Block




            -- available online in file 'sample2'

                         DECLARE

                        CURSOR c1 is

            SELECT ename, empno, sal FROM emp

    ORDER BY sal DESC; -- start with highest paid employee

                my_ename VARCHAR2(10);

                  my_empno NUMBER(4);

                  my_sal NUMBER(7,2);

                          BEGIN

                          OPEN c1;

                     FOR i IN 1..5 LOOP

        FETCH c1 INTO my_ename, my_empno, my_sal;

EXIT WHEN c1%NOTFOUND; /* in case the number requested */

                       /* is more than the total    */

                       /* number of employees       */

 INSERT INTO temp VALUES (my_sal, my_empno, my_ename);

                           COMMIT;

                         END LOOP;

                         CLOSE c1;

                           END;


                   Output Table



     SQL> SELECT * FROM temp ORDER BY col1 DESC;
NUM_COL1 NUM_COL2 CHAR_COL

                                    -------- -------- --------

                                      5000      7839 KING

                                      3000      7902 FORD

                                      3000     7788 SCOTT

                                     2975      7566 JONES

                                      2850     7698 BLAKE




                                 TRIGGER PROGRAM

This trigger will insert a record into the table 'product_check' before a sql
             update statement is executed, at the statement level.

               CREATE or REPLACE TRIGGER After_Update_Row_product

                                            AFTER

                                     insert On product

                                     FOR EACH ROW

                                             BEGIN

                              INSERT INTO product_check

                        Values('After update, Row level',sysdate);

                                             END;

                                                /

                  Now lets execute a update statement on table product.




                        UPDATE PRODUCT SET unit_price = 800

                             WHERE product_id in (100,101);

Lets check the data in 'product_check' table to see the order in which the trigger is fired.
SELECT * FROM product_check;

                             Output:




     Mesage                                    Current_Date




    ------------------------------------------------------------




     Before update, statement level            26-Nov-2008

  Before update, row level                        26-Nov-2008

After update, Row level                             26-Nov-2008

Before update, row level                            26-Nov-2008

After update, Row level                              26-Nov-2008

     After update, statement level              26-Nov-2008

More Related Content

What's hot

12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMSkoolkampus
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMSkoolkampus
 
Buffer management --database buffering
Buffer management --database buffering Buffer management --database buffering
Buffer management --database buffering julia121214
 
Introduction to Data Abstraction
Introduction to Data AbstractionIntroduction to Data Abstraction
Introduction to Data AbstractionDennis Gajo
 
Distributed operating system
Distributed operating systemDistributed operating system
Distributed operating systemPrankit Mishra
 
Object Oriented Programming Principles
Object Oriented Programming PrinciplesObject Oriented Programming Principles
Object Oriented Programming PrinciplesAndrew Ferlitsch
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bankArthyR3
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Operating Systems 1 (8/12) - Concurrency
Operating Systems 1 (8/12) - ConcurrencyOperating Systems 1 (8/12) - Concurrency
Operating Systems 1 (8/12) - ConcurrencyPeter Tröger
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 

What's hot (20)

Sql fundamentals
Sql fundamentalsSql fundamentals
Sql fundamentals
 
Recursion
RecursionRecursion
Recursion
 
Master theorem
Master theoremMaster theorem
Master theorem
 
Compiler Design Unit 1
Compiler Design Unit 1Compiler Design Unit 1
Compiler Design Unit 1
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
 
12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS12. Indexing and Hashing in DBMS
12. Indexing and Hashing in DBMS
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMS
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
Buffer management --database buffering
Buffer management --database buffering Buffer management --database buffering
Buffer management --database buffering
 
Introduction to Data Abstraction
Introduction to Data AbstractionIntroduction to Data Abstraction
Introduction to Data Abstraction
 
14 Skip Lists
14 Skip Lists14 Skip Lists
14 Skip Lists
 
Distributed operating system
Distributed operating systemDistributed operating system
Distributed operating system
 
Object Oriented Programming Principles
Object Oriented Programming PrinciplesObject Oriented Programming Principles
Object Oriented Programming Principles
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Operating Systems 1 (8/12) - Concurrency
Operating Systems 1 (8/12) - ConcurrencyOperating Systems 1 (8/12) - Concurrency
Operating Systems 1 (8/12) - Concurrency
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 

Viewers also liked (20)

Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
TRIGGERS
TRIGGERSTRIGGERS
TRIGGERS
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Basic cursors in oracle
Basic cursors in oracleBasic cursors in oracle
Basic cursors in oracle
 
Triggers ppt
Triggers pptTriggers ppt
Triggers ppt
 
Triggers-Sequences-SQL
Triggers-Sequences-SQLTriggers-Sequences-SQL
Triggers-Sequences-SQL
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Trigger
TriggerTrigger
Trigger
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Trigger
TriggerTrigger
Trigger
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Plsql
PlsqlPlsql
Plsql
 
Joins SQL Server
Joins SQL ServerJoins SQL Server
Joins SQL Server
 

Similar to Trigger and cursor program using sql

Oracle Database 12c Application Development
Oracle Database 12c Application DevelopmentOracle Database 12c Application Development
Oracle Database 12c Application DevelopmentSaurabh K. Gupta
 
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلحل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلMohamed Moustafa
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersConnor McDonald
 
Restricting and sorting data
Restricting and sorting data Restricting and sorting data
Restricting and sorting data HuzaifaMushtaq3
 
Analytic functions in Oracle SQL - BIWA 2017
Analytic functions in Oracle SQL - BIWA 2017Analytic functions in Oracle SQL - BIWA 2017
Analytic functions in Oracle SQL - BIWA 2017Connor McDonald
 
ILOUG 2019 - SQL features for Developers
ILOUG 2019 - SQL features for DevelopersILOUG 2019 - SQL features for Developers
ILOUG 2019 - SQL features for DevelopersConnor McDonald
 
Les02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting DataLes02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting Datasiavosh kaviani
 
Sangam 19 - Analytic SQL
Sangam 19 - Analytic SQLSangam 19 - Analytic SQL
Sangam 19 - Analytic SQLConnor McDonald
 
The Five Best Things To Happen To SQL
The Five Best Things To Happen To SQLThe Five Best Things To Happen To SQL
The Five Best Things To Happen To SQLConnor McDonald
 
OpenWorld 2018 - Common Application Developer Disasters
OpenWorld 2018 - Common Application Developer DisastersOpenWorld 2018 - Common Application Developer Disasters
OpenWorld 2018 - Common Application Developer DisastersConnor McDonald
 
SQL WORKSHOP::Lecture 2
SQL WORKSHOP::Lecture 2SQL WORKSHOP::Lecture 2
SQL WORKSHOP::Lecture 2Umair Amjad
 

Similar to Trigger and cursor program using sql (20)

Les06 Subqueries
Les06 SubqueriesLes06 Subqueries
Les06 Subqueries
 
Oracle Database 12c Application Development
Oracle Database 12c Application DevelopmentOracle Database 12c Application Development
Oracle Database 12c Application Development
 
Les12 creating views
Les12 creating viewsLes12 creating views
Les12 creating views
 
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلحل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developers
 
Sql2
Sql2Sql2
Sql2
 
Restricting and sorting data
Restricting and sorting data Restricting and sorting data
Restricting and sorting data
 
chap2 (3).ppt
chap2 (3).pptchap2 (3).ppt
chap2 (3).ppt
 
Analytic functions in Oracle SQL - BIWA 2017
Analytic functions in Oracle SQL - BIWA 2017Analytic functions in Oracle SQL - BIWA 2017
Analytic functions in Oracle SQL - BIWA 2017
 
Cube rollup slides
Cube rollup slidesCube rollup slides
Cube rollup slides
 
Les02.pptx
Les02.pptxLes02.pptx
Les02.pptx
 
ILOUG 2019 - SQL features for Developers
ILOUG 2019 - SQL features for DevelopersILOUG 2019 - SQL features for Developers
ILOUG 2019 - SQL features for Developers
 
ORACLE NOTES
ORACLE NOTESORACLE NOTES
ORACLE NOTES
 
Les02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting DataLes02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting Data
 
Sangam 19 - Analytic SQL
Sangam 19 - Analytic SQLSangam 19 - Analytic SQL
Sangam 19 - Analytic SQL
 
Les02 Restricting And Sorting Data
Les02 Restricting And Sorting DataLes02 Restricting And Sorting Data
Les02 Restricting And Sorting Data
 
The Five Best Things To Happen To SQL
The Five Best Things To Happen To SQLThe Five Best Things To Happen To SQL
The Five Best Things To Happen To SQL
 
OpenWorld 2018 - Common Application Developer Disasters
OpenWorld 2018 - Common Application Developer DisastersOpenWorld 2018 - Common Application Developer Disasters
OpenWorld 2018 - Common Application Developer Disasters
 
Oracle
OracleOracle
Oracle
 
SQL WORKSHOP::Lecture 2
SQL WORKSHOP::Lecture 2SQL WORKSHOP::Lecture 2
SQL WORKSHOP::Lecture 2
 

More from Sushil Mishra

Heart beat monitor using AT89S52 microcontroller
Heart beat monitor using AT89S52 microcontrollerHeart beat monitor using AT89S52 microcontroller
Heart beat monitor using AT89S52 microcontrollerSushil Mishra
 
Consumer electronics lab manual
Consumer electronics lab manualConsumer electronics lab manual
Consumer electronics lab manualSushil Mishra
 
Summer training at Doordarshan presentation
Summer training at Doordarshan presentationSummer training at Doordarshan presentation
Summer training at Doordarshan presentationSushil Mishra
 
List of microcontroller 8051 projects
List of microcontroller 8051 projectsList of microcontroller 8051 projects
List of microcontroller 8051 projectsSushil Mishra
 
Sequence Diagram of Hotel Management System
Sequence Diagram of Hotel Management SystemSequence Diagram of Hotel Management System
Sequence Diagram of Hotel Management SystemSushil Mishra
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointersSushil Mishra
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!Sushil Mishra
 
Tachometer using AT89S52 microcontroller with motor control
Tachometer using AT89S52 microcontroller with motor controlTachometer using AT89S52 microcontroller with motor control
Tachometer using AT89S52 microcontroller with motor controlSushil Mishra
 
Report on industrial training at DDK, Mandi House, Delhi -01
Report on industrial training at DDK, Mandi House, Delhi -01Report on industrial training at DDK, Mandi House, Delhi -01
Report on industrial training at DDK, Mandi House, Delhi -01Sushil Mishra
 
Mythological calender using C++
Mythological calender using C++Mythological calender using C++
Mythological calender using C++Sushil Mishra
 
Laser, its working & hazards
Laser, its working & hazardsLaser, its working & hazards
Laser, its working & hazardsSushil Mishra
 
Designing a notch filter using orcad 15.3
Designing a notch filter using orcad 15.3Designing a notch filter using orcad 15.3
Designing a notch filter using orcad 15.3Sushil Mishra
 

More from Sushil Mishra (14)

Heart beat monitor using AT89S52 microcontroller
Heart beat monitor using AT89S52 microcontrollerHeart beat monitor using AT89S52 microcontroller
Heart beat monitor using AT89S52 microcontroller
 
Opt sim manual
Opt sim manualOpt sim manual
Opt sim manual
 
Consumer electronics lab manual
Consumer electronics lab manualConsumer electronics lab manual
Consumer electronics lab manual
 
Summer training at Doordarshan presentation
Summer training at Doordarshan presentationSummer training at Doordarshan presentation
Summer training at Doordarshan presentation
 
List of microcontroller 8051 projects
List of microcontroller 8051 projectsList of microcontroller 8051 projects
List of microcontroller 8051 projects
 
Sequence Diagram of Hotel Management System
Sequence Diagram of Hotel Management SystemSequence Diagram of Hotel Management System
Sequence Diagram of Hotel Management System
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointers
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!
 
Tachometer using AT89S52 microcontroller with motor control
Tachometer using AT89S52 microcontroller with motor controlTachometer using AT89S52 microcontroller with motor control
Tachometer using AT89S52 microcontroller with motor control
 
Report on industrial training at DDK, Mandi House, Delhi -01
Report on industrial training at DDK, Mandi House, Delhi -01Report on industrial training at DDK, Mandi House, Delhi -01
Report on industrial training at DDK, Mandi House, Delhi -01
 
Quiz using C++
Quiz using C++Quiz using C++
Quiz using C++
 
Mythological calender using C++
Mythological calender using C++Mythological calender using C++
Mythological calender using C++
 
Laser, its working & hazards
Laser, its working & hazardsLaser, its working & hazards
Laser, its working & hazards
 
Designing a notch filter using orcad 15.3
Designing a notch filter using orcad 15.3Designing a notch filter using orcad 15.3
Designing a notch filter using orcad 15.3
 

Trigger and cursor program using sql

  • 1. AIM: TRIGGER AND CURSOR PROGRAM USING SQL INTRODUCTION: In SQL procedures, a cursor make it possible to define a result set (a set of data rows) and perform complex logic on a row by row basis. By using the same mechanics, an SQL procedure can also define a result set and return it directly to the caller of the SQL procedure or to a client application. A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only reference one row at a time, but can move to other rows of the result set as needed. To use cursors in SQL procedures, you need to do the following: 1)Declare a cursor that defines a result set. 2)Open the cursor to establish the result set. 3)Fetch the data into local variables as needed from the cursor, one row at a time. 4)Close the cursor when done. The SQL CREATE TRIGGER statement provides a way for the database management system to actively control, monitor, and manage a group of tables
  • 2. whenever an insert, update, or delete operation is performed. The statements specified in the SQL trigger are executed each time an SQL insert, update, or delete operation is performed. An SQL trigger may call stored procedures or user- defined functions to perform additional processing when the trigger is executed. CURSOR PROGRAM: The following PROGRAM uses a cursor to select the five highest paid employees from the emp table. Input Table SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC; ENAME EMPNO SAL ---------- --------- -------- KING 7839 5000 SCOTT 7788 3000 FORD 7902 3000 JONES 7566 2975 BLAKE 7698 2850 CLARK 7782 2450 ALLEN 7499 1600 TURNER 7844 1500 MILLER 7934 1300 WARD 7521 1250 MARTIN 7654 1250 ADAMS 7876 1100
  • 3. JAMES 7900 950 SMITH 7369 800 PL/SQL Block -- available online in file 'sample2' DECLARE CURSOR c1 is SELECT ename, empno, sal FROM emp ORDER BY sal DESC; -- start with highest paid employee my_ename VARCHAR2(10); my_empno NUMBER(4); my_sal NUMBER(7,2); BEGIN OPEN c1; FOR i IN 1..5 LOOP FETCH c1 INTO my_ename, my_empno, my_sal; EXIT WHEN c1%NOTFOUND; /* in case the number requested */ /* is more than the total */ /* number of employees */ INSERT INTO temp VALUES (my_sal, my_empno, my_ename); COMMIT; END LOOP; CLOSE c1; END; Output Table SQL> SELECT * FROM temp ORDER BY col1 DESC;
  • 4. NUM_COL1 NUM_COL2 CHAR_COL -------- -------- -------- 5000 7839 KING 3000 7902 FORD 3000 7788 SCOTT 2975 7566 JONES 2850 7698 BLAKE TRIGGER PROGRAM This trigger will insert a record into the table 'product_check' before a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER After_Update_Row_product AFTER insert On product FOR EACH ROW BEGIN INSERT INTO product_check Values('After update, Row level',sysdate); END; / Now lets execute a update statement on table product. UPDATE PRODUCT SET unit_price = 800 WHERE product_id in (100,101); Lets check the data in 'product_check' table to see the order in which the trigger is fired.
  • 5. SELECT * FROM product_check; Output: Mesage Current_Date ------------------------------------------------------------ Before update, statement level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 After update, statement level 26-Nov-2008