DBMSLabManual Suresh

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 34

DEPARTMENT OF MCA

DBMS LAB

Prepared by M SURESH

SPHOORTHY ENGINEERING COLLEGE

Department of MCA

DBMS Lab Manual

TABLE OF CONTENTS S. No 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 Topic Lab Objectives Lab Plan Introduction Unit I Experiment 1 Experiment 2 Experiment 3 Experiment 4 Experiment 5 Experiment 6 Experiment 7 Experiment 8 Experiment 9 Experiment 10 Experiment 11 Experiment 12 Experiment 13 Experiment 14 Experiment 15 Experiment 16 Experiment 17 Experiment 18 Experiment 19 Additional Exercises for Unit I Unit II Experiment 20 Experiment 21 Experiment 22 Experiment 23 Experiment 24 Experiment 25 Experiment 26 Experiment 27 Experiment 28 Experiment 29 Experiment 30 Experiment 31 Page No 4 5 7 8 10 10 10 11 11 11 11 12 12 12 13 13 13 13 14 14 14 14 15 16 17 21 21 21 21 22 22 22 22 23 23 23 23 2

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

Experiment 32 Additional Exercises for Unit II Unit III Experiment 33 Experiment 34 Experiment 35 Experiment 36 Experiment 37 Experiment 38 Experiment 39 Experiment 40 Experiment 41 Experiment 42 Additional Exercises for Unit III Supplementary Exercises References

23 25 26 29 29 29 30 30 30 30 31 31 31 32 33 33

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

LAB OBJECTIVES A vast majority of the software applications being built use some kind of a data store mechanism to permanently store the data generated/used by the software. Database management systems are complex software systems that provide a wide variety of functionality for users to structure, organize and access data quickly and efficiently. Database systems have been there since the early 1970s but have grown in complexity and size. Relational database management systems use relational algebra as the basis for representation of data. RDBMS as relational database management systems are the most popular and widely used DBMS in the market place. In this lab, you would be exposed to one popular RDBMS. The broad one line objective of the lab is to get familiar with the functionality and support provided by commercially popular RDBMS and understand how to use it to meet your data storage and organization requirements. Detailed objectives of the lab are: You learn SQL (Structured Query Language) which would provide functionality to: o Learn how to create tables which are fundamental storage blocks of data. o Learn how to place constraints on data that is entered on tables to ensure data integrity. o Learn how to add, change and remove data from tables. o Learn how to select a subset of the data you want to see from the collection of tables and data. o Learn how to combine table and group multiple rows of data in table. You learn PL/SQL which would provide the ability to do iterative programming at database level to: o Write programming blocks with conditionals, assignments, loops, etc o Exception Handling. o Transaction oriented programs o Stored procedures, functions, packages. o Cursors which would allow row wise access of data. o Triggers which would allow you define pre and post actions when something changes in the database tables.

At the end of the lab, you should be comfortable using any popular RDBMS for data access and updating and should be comfortable writing PL/SQL programs at database level using Oracle.

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

LAB PLAN Introduction: Week 1: Oracle 9i setup & connecting to Oracle from SQL*Plus. Unit I (SQL): Week 2: Creating, Altering, Dropping tables with Constraints, Insert Table. Experiment 1: Create Tables Experiment 2: Alter table with changes in columns Experiment 3: Alter table with constraints Experiment 4: Dropping Tables Experiment 5: Inserting Data into Tables. Week 3: Inserting, Simple Select, Char, Number, Date functions Experiment 6: Simple Select Experiment 7: Select with conditions. Experiment 8: Using character functions. Experiment 9: Using number functions. Experiment 10: Using date functions. Week 4: Detailed SELECT with sub-queries, EQUI-JOINS, correlated sub-queries. Experiment 11: Single row sub-queries. Experiment 12: Multiple row sub-queries. Experiment 13: Equal joins. Experiment 14: correlated sub-queries. Week 5: GROUPING, SET, UPDATE, DELETE, VIEWS Experiment 15: Aggregate functions. Experiment 16: Grouping clauses Experiment 17: Select groups with having Experiment 18: Union/Intersection statements Experiment 19: Creating and dropping views. Week 6: Back Logs, if any and/or Additional Exercises for Unit I.

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

Unit II (PL/SQL: Program Development): Week 7: Iterative PL/SQL Blocks and functions. Experiment 20: Simple PL/SQL Blocks Experiment 21: Nested IF and CASE in PL/SQL Experiment 22: NULLIF and COALESCE functions Experiment 23: WHILE & FOR Loops Week 8: Transaction support in PL/SQL Experiment 24: COMMIT & ROLLBACK Experiment 25: SAVEPOINTS Week 9: Exception support in PL/SQL Experiment 26: Exception Blocks Experiment 27: BUILT-IN Exceptions Experiment 28: User defined Exceptions Experiment 29: Raising application error Week 10: Functions, Procedures, Packages Experiment 30: Creating Stored Procedures with Parameters. Experiment 31: Creating Stored Functions with Parameters. Experiment 32: Grouping Stored Packages. Week 11: Back Logs, if any and/or Additional Exercises for Unit II. Unit III (PL/SQL: Cursors & Triggers) Week 12: Declare, Fetch, Open, and Close Cursors Experiment 33: Declaring Cursors. Experiment 34: Opening & Closing Cursors. Experiment 35: Fetch from an open Cursor. Experiment 36: Accessing current row in the cursor. Week 13: Before & After [Row and Statement Triggers], Instead of Triggers. Experiment 37: Creating Before Statement Trigger. Experiment 38: Creating After Statement Trigger. Experiment 39: Creating Before Row Trigger. Experiment 40: Creating After Row Trigger. Experiment 41: Creating Triggers with when condition. Experiment 42: Creating instead of triggers to replaces updating from views.

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

Week 14: Back Logs, if any and/or Additional Exercises for Unit III

Introduction RDBMS is one of the most widely used pluggable software components in most enterprise software applications. Though RDBMS applications have been there since the early 1970s, they have improved tremendously in terms of their features, the size of data they can hold, and the complexity over the last 20 years. Oracle is one of the very widely used commercial RDBMS systems and at this point is the market leader as far as RDBMS is concerned. Oracle9i is RDBMS software which supports SQL 1999. It also supports programming language extension to SQL called PL/SQL which is Oracle proprietary and is very popular to do program development at the database server level. Other popular DBMS software like Sybase and SQL Server support their own programming extensions to SQL 1999.

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

UNIT I (SQL) SQL (Structured Query Language) is a standard supported by all the popular relational database management systems in the market place. The basis data structure in RDBMS is a table. SQL provides you the features to define tables, define constraints on tables, query for data in table, and change the data in table by adding, modifying, and removing data. SQL also supports grouping of data in multiple rows, combining tables and other features. All these put together, SQL is a high-level query language standard to access and alter data in RDBMS. Querying for Data: The typical syntax to query for data is; SELECT clause FROM clause WHERE clause There are of course a few other additions to these standard clauses. GROUP BY HAVING

Querying can be used to: To retrieve existing data from database. Get all data from the table Get selected columns from the table. Get selected rows from the table. Get selected columns of selected rows from the table. Get computed columns using char, number, data functions, general functions, and aggregating functions. Get data in multiple rows grouped on an aggregating function applied on one or more columns. Select specific aggregating data on multiple rows using having clause. Apply set operations like Union and Intersection on data sets of the same cardinality and type. Get data from multiple tables using Cartesian product, equality join, un-equal join, and outer join. Create views on physical data. Data Definition Language (DDL): To do with altering the structure of data base. SPHOORTHY Engineering College 8

Department of MCA

DBMS Lab Manual

Create tables. Create Indexes on tables. Alter tables Add constraints to tables. Drop tables. Truncate tables. Drop indexes. Create sequences.

Data Manipulation Language (DML): To do with adding, updating, and deleting data from tables. Insert Data Update Data Delete Data Merge Tables. Data Control Language (DCL): To do with controlling access to data in tables. Grant Permissions Revoke Permissions Create and update roles. Add users to roles.

As you can see from above, SQL gives you all the tools needed to define your database in the form of table, define integrity constraint rules on table to ensure data integrity, change the database as needed and control permissions on tables at a very fine granular level. SQL 1999 is the standard which is supported by all commercial database vendors. If your queries are using SQL 1999 standard, they will run all RDBMS servers. In addition to the SQL 1999 standard, most commercial databases have their own extensions to SQL supported by them. In the interest of portability, it would be good if we stick with SQL 1999 standard in our querying no matter what RDBMS we are using unless we have a strong reason to go for additional features not included in SQL 1999 standard.

SPHOORTHY Engineering College

Department of MCA

DBMS Lab Manual

Experiment I: Problem Statement: Create location, department, job_grade, and employee tables with the following columns. Location: (location_id:number, city:string) Department: (department_id:number, department_name:string, head:number, department_location:number) Job_grade: (job_grade:string, lower_bound:number, upper_bound:number) Employee: (employee_id:number, first_name:string, last_name:string, join_date:date, manager_id:number, salary:number) Solution: 1. Understand create table syntax. 2. Decide the name of the table. 3. Decide the name of each column and its data type. 4. Use the create table syntax to create the said tables. 5. Create primary key constraint for each table as understand from logical table structure. Experiment 2: Problem Statement: Alter employee table to add job_grade column which is of string data type. Solution: 1. Learn alter table syntax. 2. Define the new column and its data type. 3. Use the alter table syntax. Experiment 3: Problem Statement: Alter employee table to make job_grade a foreign key to job_grade table, manager_id a foreign key to employee table, department_id a foreign key to department table. Solution: 4. Learn alter table syntax. SPHOORTHY Engineering College 10

Department of MCA

DBMS Lab Manual

5. Define the new constraint [type, name, columns effected] 6. Use the alter table syntax for adding constraints.

Experiment 4: Problem Statement: Create a dummy table called my_employee with the same definition as employee table and than drop the table. Solution: 1. Use create table to create my_employee. 2. Use drop table to drop my_employee. Experiment 5: Problem Statement: Insert data into location, department, job_grade & employee tables. Solution: 1. Decide the data to add in location. 2. Add to location one row at a time using insert into syntax 3. Decide the data to add in department. 4. Add to department one row at a time using insert into syntax. 5. Decide the data to add in job_grade. 6. Add to job_grade one row at a time using the insert into syntax. 7. Decide the data to add in employee. 8. Add to employee one row at a time using the insert into syntax. Experiment 6: Problem Statement: Give a list of all employees (names as first_name, last_name) who belong to one department_id. Solution: 1. use SELECT FROM WHERE syntax. 2. select should include first_name and last_name in the given format. 3. from should include employee 4. where should include condition on department_id SPHOORTHY Engineering College 11

Department of MCA

DBMS Lab Manual

Experiment 7: Problem Statement: Select employee last_names from employee table who belong to a certain department_id and have a salary greater than 5000. Solution: 1. Use SELECT FROM WHERE syntax. 2. Use AND operator for 2 conditions in WHERE. Experiment 8: Problem Statement: Select employee last_name with first letter in capital, all smalls and all capitals from employee table for all employees. Solution: 1. Use select from where clause. 2. Use initcap, lower, and upper functions on last_name in select clause to get the result. Experiment 9: Problem Statement: Select the salary and additional HRA (7.5% of the salary) for each employee in employee table rounded to a whole number. Solution: 1. Use select from where clause and arithmetic to compute HRA. 2. Use the round function to round off the computed HRA to the nearest whole number. Experiment 10: Problem Statement: Select employee last_name, join_date, and the number of days he/she has been working in the firm as of today. Solution: 1. Use the select from where clause. SPHOORTHY Engineering College 12

Department of MCA

DBMS Lab Manual

2. In the clause, get the current data using sysdate function, get the difference between sysdate and employee joining date and compute the days in between using the days_between date function. 3. Show the join_date using mm/dd/yyyy format to using to_char function.

Experiment 11: Problem Statement: Select employee last_name of all employees whose salary is greater than the salary of employee with id = 2. Solution: 1. Use an inner query to first get the salary of employee_id = 2. 2. The result from the inner query is than given in the where clause of the outer query that selects all employees with salary greater than that. Experiment 12: Problem Statement: Select all employees whose salary is greater than the salaries of both employees with ids 2 & 3. Solution: 3. Use an inner query to first get the salary of employee_id in (2,3). 4. The result from the inner query is than given in the where clause of the outer query using the all operator that selects all employees with salary greater than that. Experiment 13: Problem Statement: Select employee lastname and the corresponding department_name for all employees in employees table. Solution: 1. Use select from where clause with the from coming from employee and department tables and a condition joining these two table using the foreign key department_id which connects both the tables with an equality condition. Experiment 14: SPHOORTHY Engineering College 13

Department of MCA

DBMS Lab Manual

Problem Statement: Select all employees whose salary is lesser than all employees in the same job grade. Solution: 1. Use the correlated sub-query where the inner query will be made based on the data coming from the upper query. In this case, the salary and grade of each employee row is used to execute the inner query to compare if there are any employees in the same grade who have lesser salary using exists clause. Experiment 15: Problem Statement: Select the average salary of all employees in department with department_id = 2. Solution: 1. Use the AVG aggregate function in select clause. 2. Use the department_id = 2 condition in where clause. Experiment 16: Problem Statement: Select AVG salary of each department which has employees in employee table. Solution: 1. Use the AVG aggregate function in select clause. 2. Since we want average per department, have department_id in select clause. 3. Include a grouping clause by department_id to indicate you want to aggregate data by department_id Experiment 17: Problem Statement: Select minimum salary of all departments where the minimum salary is less than 1000. Solution: 4. Use the MIN aggregate function in select clause. 5. Since we want average per department, have department_id in select clause. 6. Include a grouping clause by department_id to indicate you want to aggregate data by department_id. 7. Exclude groupings which have a minimum salary greater than 1000 using having clause. SPHOORTHY Engineering College 14

Department of MCA

DBMS Lab Manual

Experiment 18: Problem Statement: Give a list of all employees who earn a salary greater than 10000 or work in job grade MANAGER.

Solution: 1. Write a select from where which gives all employees with salary greater than 10000. 2. Write a select from where which gives all employees whose job grade in manager. 3. Combine them using UNION clause. Experiment 19: Problem Statement: Create a view that shows all employees of department_id = 10 and select from the view. Solution: 1. Create view with the select clause on employees table with the said condition. 2. Write a select statement using the view created instead of table whenever you need employees of department_id = 10.

SPHOORTHY Engineering College 15

Department of MCA

DBMS Lab Manual

Unit I Additional Exercises 1. Write a query that would give the employee name, his salary and the lower end and higher end salaries of his job grade? 2. Write a query that would give the employee name and his department name using natural join. 3. Write a query which would give all employee names and their department names. The query should also return employees who are currently not allotted to any department and departments that do not have any employees. 4. Write a query to merge department level employee table data changes to college level employee table on a periodic basis. 5. I want to insert a lot of records in employee table which has certain constraints on salary. I know all records I am inserting would be good in salary field. Trying inserting as is and with the salary constraint disable before bulk insert and enable after insert and see the time difference. 6. Create index of salary column of employee and search for all employees with a certain salary. 7. Instead of giving a unique ID yourself, what can be done to automatically generate unique ID.

SPHOORTHY Engineering College 16

Department of MCA

DBMS Lab Manual

UNIT II (PL/SQL) PL/SQL is the procedural extension to SQL with design features of programming languages. Data manipulation and query statements of SQL are included within procedural units of code. Benefits of PL/SQL: PL/SQL can improve the performance of an application. The benefits differ depending on the execution environment: PL/SQL can be used to group SQL statements together within a single block and to send the entire block to the server in a single call thereby reducing networking traffic. Without PL/SQL, the SQL statements are sent to the Oracle server one at a time. Each SQL statement results in another call to the Oracle server and higher performance overhead. In a network environment, the overhead can become significant. PL/SQL can also operate with Oracle server application development tools such as Oracle forms and Oracle reports.

PL/SQL Block Structure: Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate or nested one within another. The basic units (procedures, functions, and anonymous blocks) that make up a PL/SQL program are logical blocks which can contain any number of nested sub-blocks. Therefore one block can represent a small part of another block, which in turn can be part of the whole unit of code. Modularized program development: Group logically related statements within blocks. Nest sub-blocks inside larger blocks to build powerful programs. SPHOORTHY Engineering College 17

Department of MCA

DBMS Lab Manual

Break down a complex problem into a set of manageable well defined logical modules and implement the modules with blocks. Place reusable PL/SQL code in libraries to be shared between Oracle forms and Oracle reports, applications, or store it in a Oracle server to make it accessible to any application that can interact with an Oracle database.

Identifiers/Variables: In PL/SQL, you can use identifiers to do the following: Declare variables, cursors, constants and exceptions and then use them in SQL and procedural statements. Declare variables belonging to scalar, reference, composite and large object (LOB) data types. Declare variables dynamically based on the data structure of tables and columns in the database. Procedural Language Control Structures: Execute a sequence of statements conditionally. Execute a sequence of statements iteratively in a loop. Process individually the rows returned by a multiple row query with a cursor. Errors: Process Oracle server error with exception-handling routines. Declare user-defined error conditions and process them with exception-handling routines. PL/SQL Block Syntax: DECLARE [Optional] Variables, cursors, user defined exceptions BEGIN [Mandatory] - SQL Statements - PL/SQL Statements Exception [Optional] -- Actions to be performed when errors occur ---END [Mandatory]; Example: DECLARE v_variable VARCHAR2(5); BEGIN SELECT column_name INTO v_variable FROM table_name; EXCEPTION WHEN exception_name THEN SPHOORTHY Engineering College 18

Department of MCA

DBMS Lab Manual

END; Anonymous, procedure and function blocks: Anonymous: - No name. - Starts with DECLARE statement. Procedure: - No return. - PROCEDURE name IS Function: - Returns a value - FUNCTION name RETURN data-type IS Programming Constructs: - Declaring Variables: o Identifier [CONSTANT] data-type [NOT NULL] [:= | DEFAULT expr]; Assignment: o Identifier := expr; IF Statement: o IF condition THEN Statements; [ELSE IF condition THEN Statements;] [ELSE Statements;] END IF; CASE Statement: o CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 . . . WHEN expression THEN resultn [ELSE resultn1;]

SPHOORTHY Engineering College 19

Department of MCA

DBMS Lab Manual

END; BASIC Loops: o LOOP Statement 1; . . . EXIT [WHEN condition]; END LOOP; WHILE Statement: o WHILE condition LOOP Statement1; . . . END LOOP; FOR Statement: o FOR counter IN [REVERSE] Lower_bound..upper_bound LOOP Statement1; . . . END LOOP;

Packages: Packages are collections of variables, user defined data types, procedures and functions which can either be either public or private. Packages are used to group related things into one block that get loads into memory in one go. A package cannot be invoked directly.

SPHOORTHY Engineering College 20

Department of MCA

DBMS Lab Manual

Experiment 20: Problem Statement: Write a PL/SQL block which declares a variable and reads the last name of employee with id = 5 and outputs that to standard output. Solution: 1. Declare a varchar variable 2. Write the select into clause inside PL/SQL Begin END block. Experiment 21: Problem Statement: Write a PL/SQL block which declares a variable with a value and prints in all capitals if the value starts with S, in all smalls if it starts with R, and in initial capitals if otherwise. Solution: 1. Use IF or CASE. Experiment 22: Problem Statement: Write a PL/SQL block which declares two variables with values and prints first value if it is not null and prints second value if first is null. Solution: SPHOORTHY Engineering College 21

Department of MCA

DBMS Lab Manual

Use NULLIF or COALESCE. Experiment 23: Problem Statement: Write a PL/SQL block which declares a variable and reads the last name of employees and outputs that to standard output. Solution: 3. Declare a varchar variable 4. Write a LOOP.

Experiment 24: Problem Statement: Write a PL/SQL block which updates 2 tables. If the second update fails the first update also has to be reversed. Solution: 1. Use BEGIN transaction, END transaction. 2. Check for success of a query. 3. Use ROLLBACK or COMMIT depending on query success. Experiment 25: Problem Statement: Write a PL/SQL block which updates 3 tables. If the third update fails the second update has to be reversed while first should not get effected. Solution: 1. Use BEGIN transaction, END transaction. 2. Define SAVEPOINT at the end of first update. 3. Run 3rd update and check for success. 4. If 3rd fails, Use ROLLBACK to SAVEPOINT. Experiment 26: Problem Statement: SPHOORTHY Engineering College 22

Department of MCA

DBMS Lab Manual

Write a PL/SQL block with a simple Exception Block. Solution: 1. Refer to Exception block syntax. Experiment 27: Problem Statement: Write a PL/SQL block which declares a variable and reads the last name of employee with id = 5. If there is no employee with id = 5 an error should be thrown. Otherwise the name has to be printed. Solution: 1. Use built-in exceptions.

Experiment 28: Problem Statement: Write a PL/SQL block which declares a variable and reads the last name of employee with id = 5. If the name has 8 characters, raise an exception called too many characters and handle it by cutting the last_name to first eight characters. Solution: 1. Use user defined exceptions. Experiment 29: Problem Statement: Think of a problem that generates an exception is caught but an application error has to be raised because the exception in fatal. Solution: 1. As a part of exception handling, raise application error if the situation is not recoverable. Experiment 30: Problem Statement: Create a stored procedure which takes deparment_id as parameter, inserts all employees of that department in a table called dept_employee with the same structure. SPHOORTHY Engineering College 23

Department of MCA

DBMS Lab Manual

Solution: 1. Learn how to use parameter in to stored procedure. Experiment 31: Problem Statement: Create a function which takes deparment_id as parameter and returns the name of the department. Solution: 1. Learn how to use parameter in functions. Experiment 32: Problem Statement: Write a package which implements a set of functions that will compute HRA, DA based on rules given salary. Solution: 1. Implement one stored function that will compute HRA given basic. 2. Implement one stored function that will compute DA given basic. 3. Put these in a package so it gets loaded at one time.

SPHOORTHY Engineering College 24

Department of MCA

DBMS Lab Manual

Unit II Additional Exercises 1. Write a PL/SQL procedure which takes department id as parameter and gives all employees belong to the department. 2. Write a PL/SQL procedure which takes lowest and highest salary as parameters and returns all employees with-in that salary range. If there re no employees, an exception has to be raised and an application error to be given? 3. Write a PL/SQL procedure where you define your own user exceptions and handle exceptions appropriately.

SPHOORTHY Engineering College 25

Department of MCA

DBMS Lab Manual

Unit III (Cursors & Triggers) Cursors: Every SQL statement executed by the Oracle server has an individual cursor associated with it and are called implicit cursors. There are two types of cursors. Implicit cursors: Declared for all DML and PL/SQL SELECT statements. Explicit cursors: Declared and names by the programmer. Explicit Cursors: o Individually process each row returned by a multiple row select statement. o A PL/SQL program opens a cursor, processes rows returned by a query, and then closes the cursor. The cursor marks the current position in the active set. o Can process beyond the first row returned by the query, row by row. o Keep track of which row is currently being processed. o Allow the programmer to manually control explicit cursors in the PL/QL block. Controlling Explicit Cursors: o Declare the cursor by naming it and defining the structure of the query to be performed. Within it. SPHOORTHY Engineering College 26

Department of MCA

DBMS Lab Manual

o Open the cursor: The OPEN statement executes the query and binds the variables that are referenced. Rows identified by the query are called the active set and are now available for fetching. o Fetch data from the cursor: After each fetch, you test the cursor for any existing row. If there are no more rows to process, then you must close the cursor. o Close the cursor: The CLOSE statement releases the active set of rows. It is now possible to reopen the cursor to establish a fresh active set. Syntax: Declaring a cursor: CURSOR cursor_name IS Select_statement; Opening a cursor: OPEN cursor_name; Fetch data from a cursor: FETCH cursor_name INTO [variable1, variable2,.]| record_name]; Closing a cursor: Close cursor_name; Example: Set SERVEROUTPUT ON DECLARE V_empno employees.employee_id%TYPE; V_ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; FOR I IN 1..10 LOOP FETCH emp_cursor INTO v_empno, b_ename; DBMS_OUTPUT. PUT_LINE (TO_CHAR(v_empno) || || v_ename); END LOOP CLOSE emp_cursor; Attributes of an Explicit Cursor: o %ISOPEN [is cursor open] SPHOORTHY Engineering College 27

Department of MCA

DBMS Lab Manual

o %NOTFOUND [is row not found] o %FOUND [is row found] o %ROWCOUNT [rows returned so far] Cursors can be passed parameters. Cursors also have FOR UPDATE option which allows more fine grained control of locking at a table level. WHERE CURRENT OF can be used to apply the update or delete operation to current row in the cursor. Triggers: What are triggers? A trigger is a PL/SQL block or a PL/SQL procedure associated with a table, view, schema, of the database. It executes implicitly whenever a particular event takes place. It can either be: 1. Application trigger: Fires whenever an event occurs with a particular application. 2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or database. When should we use triggers? Triggers are to be used when we want to perform related actions and when we want to centralize global operations. Create stored procedures and invoke them in a trigger, if the PL/SQL code is very lengthy. The excessive use of triggers can result in complex interdependencies, which may be difficult to maintain in large applications. Triggers should not be used where functionality needed is already built into the Oracle server or when it is duplicating what is done by other triggers. Example: A trigger called check_sal which runs every time a new employee is getting inserted to enforce some rules on what should be the minimum salary. Elements in a Trigger: Trigger timing o For table: BEFORE, AFTER o For view: INSTEAD OF Trigger event: INSERT, UPDATE, OR DELETE Table name: On table, view Trigger Type: Row or statement When clause: Restricting condition Trigger body: PL/SQL block Before triggers execute the trigger body before the triggering DML event on a table. These are frequently used to determine whether that triggering statement should be SPHOORTHY Engineering College 28

Department of MCA

DBMS Lab Manual

allowed to complete. This situation enables you to eliminate unnecessary processing of the triggering statement and it eventual rollback in cases where an exception is raised in the triggering action. After triggers are used when the triggering statement is to be completed before the triggering action and to perform a different action on the same triggering statement if a BEFORE trigger is already present. Instead of Triggers are used to provide a transparent way of modifying views that cannot be modified directly through SQL DML statements because the view is not inherently modifiable. You can write INSERT, UPDATE, and DELETE statements against the view. The INSTEAD OF trigger works invisibly in the background performing the action coded in the trigger body directly on the underlying tables. Triggering user events: o INSERT o UPDATE o DELETE Trigger Components: o Statement: The trigger body executes once for the triggering event. This is the default. A statement trigger fires once, even if no rows are affected at all. o Row: The trigger body executes once for each row affected by the triggering event. A row trigger is not executed if the triggering event affects no rows. Trigger Body: The trigger body is a PL/SQL block or a call to a procedure. Syntax: CREATE [OR REPLACE] TRIGGER trigger_name Timing Event1 [OR event2 OR event3] ON table_name Trigger_body Experiment 33: Problem Statement: Define a cursor which runs through all employees who belong to department with id = 2. Solution: 1. Use Declare cursor syntax within the PL/SQL block to define the cursor with a simple query which is select from where using employee table and a condition department_id = 2 SPHOORTHY Engineering College 29

Department of MCA

DBMS Lab Manual

Experiment 34: Problem Statement: Declare a cursor which runs through all employees who belong to department with id = 2, open the cursor and close the cursor without doing anything. Solution: 1. Use open and close operations on cursors. This is similar to opening and closing file handles. Experiment 35: Problem Statement: Declare a cursor which runs through all employees who belong to department with id = 2, open the cursor and fetches one employee at a time, prints the last name and then closes the cursor after all employees are done. Solution: 1. Declare cursor. 2. Open the cursor. 3. In a loop, fetch each row of a cursor into a variable. 4. Print the variable. 5. Continue the loop till there are no more rows. 6. Close the cursor. Experiment 36: Problem Statement: Use a cursor to look at each employee who belongs to department with id 10, check the job grade and append NEW_ to all job_grades. Solution: 1. Use the WHERE CURRENT to identify the currently fetched row from cursor and run the update query. 2. This is useful for update and deletes. Experiment 37: Problem Statement: Create a trigger which writes a record called employees table being changed with time in a log table whenever anyone attempts to change employees table. Solution: SPHOORTHY Engineering College 30

Department of MCA

DBMS Lab Manual

1. We want to write a statement trigger that records the fact that someone is changing the employees table in a log table using before trigger. Experiment 38: Problem Statement: Create a trigger which writes a record called employees table has been changed with time in a log table whenever someone successfully changes the employee table. Solution: 1. We want to write a statement trigger that records the fact that some-one changed the employees table in a log table using after trigger that acts on insert, update and delete operations. Experiment 39: Problem Statement: Implement a solution that would record all attempted updates on salary in the employee table along with the employee id, old salary, new salary and the time when it was attempted in another table. Solution: 1. Use row before trigger in update operation. Experiment 40: Problem Statement: Implement a solution that would record all updates on salary in the employee table along with the employee id, old salary, new salary and the time when it was updated in another table. Solution: 1. Use row after trigger in update operation. Experiment 41: Problem Statement: Implement a solution to insert a log entry in log table whenever salary of employees with more than 20000 is revised. Solution: SPHOORTHY Engineering College 31

Department of MCA

DBMS Lab Manual

1. Write a row after trigger on employee record. 2. The trigger should work on the condition that the salary of the record is greater than 20000. Experiment 42: Problem Statement: Implement a solution which would transparently make the user feel like he is updating a view but in reality the view is read-only and a trigger is updating the base tables based on the view update given by user. Solution: 1. Use the instead of option in triggers to make trigger work in place of view and reproduce the effect intended.

Unit III Additional Exercises 8. Write a cursor which takes parameters and invoke a cursor from within a PL/SQL block. 9. Write an after trigger which acts at a row level on insert/update/delete and transfer old data to an audit trail table.

SPHOORTHY Engineering College 32

Department of MCA

DBMS Lab Manual

Supplementary Exercises 1. Design a database for library management in the college, populate data and write queries to return information like books issued, books issued to user, number of books issued, books reserved, etc. 2. Design a database for fee management in the college, populating data on fee payments, fee receipts and writing querying to return data like uncollected fees, which paid fee, etc. References Web-Sites: www.otn.oracle.com SPHOORTHY Engineering College 33

Department of MCA

DBMS Lab Manual

Books: 1. Database Management Systems, Korth & Sudharshan. 2. Database Management Systems, Raghuram Krishnan. 3. Database Management Systems, Elmasri & Navathe.

SPHOORTHY Engineering College 34

You might also like