dbmslabmanual suresh

Upload: siva-sankar

Post on 06-Apr-2018

249 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 DBMSLabManual suresh

    1/34

    DEPARTMENT OF MCA

    DBMS LAB

    Prepared by

    M SURESH

    SPHOORTHY ENGINEERING COLLEGE

  • 8/3/2019 DBMSLabManual suresh

    2/34

    Department of MCA DBMS Lab Manual

    TABLE OF CONTENTS

    S. No Topic Page No1 Lab Objectives 4

    2 Lab Plan 5

    3 Introduction 7

    4 Unit I 8

    5 Experiment 1 10

    6 Experiment 2 10

    7 Experiment 3 10

    8 Experiment 4 11

    9 Experiment 5 11

    10 Experiment 6 1111 Experiment 7 11

    12 Experiment 8 12

    13 Experiment 9 12

    14 Experiment 10 12

    15 Experiment 11 13

    16 Experiment 12 13

    17 Experiment 13 13

    18 Experiment 14 13

    19 Experiment 15 14

    20 Experiment 16 1421 Experiment 17 14

    22 Experiment 18 14

    23 Experiment 19 15

    24 Additional Exercises for Unit I 16

    25 Unit II 17

    26 Experiment 20 21

    27 Experiment 21 21

    28 Experiment 22 21

    29 Experiment 23 21

    30 Experiment 24 22

    31 Experiment 25 2232 Experiment 26 22

    33 Experiment 27 22

    34 Experiment 28 23

    35 Experiment 29 23

    36 Experiment 30 23

    37 Experiment 31 23

    SPHOORTHY Engineering College 2

  • 8/3/2019 DBMSLabManual suresh

    3/34

    Department of MCA DBMS Lab Manual

    38 Experiment 32 23

    39 Additional Exercises for Unit II 25

    40 Unit III 26

    41 Experiment 33 29

    42 Experiment 34 29

    43 Experiment 35 2944 Experiment 36 30

    45 Experiment 37 30

    46 Experiment 38 30

    47 Experiment 39 30

    48 Experiment 40 31

    49 Experiment 41 31

    50 Experiment 42 31

    51 Additional Exercises for Unit III 32

    52 Supplementary Exercises 33

    53 References 33

    SPHOORTHY Engineering College 3

  • 8/3/2019 DBMSLabManual suresh

    4/34

    Department of MCA DBMS Lab Manual

    LAB OBJECTIVES

    A vast majority of the software applications being built use some kind of a data storemechanism to permanently store the data generated/used by the software. Databasemanagement systems are complex software systems that provide a wide variety offunctionality for users to structure, organize and access data quickly and efficiently.Database systems have been there since the early 1970s but have grown in complexityand size. Relational database management systems use relational algebra as the basis forrepresentation of data. RDBMS as relational database management systems are the mostpopular and widely used DBMS in the market place.

    In this lab, you would be exposed to one popular RDBMS. The broad one line objective ofthe 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 organizationrequirements.

    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 atdatabase 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 dataaccess and updating and should be comfortable writing PL/SQL programs at databaselevel using Oracle.

    SPHOORTHY Engineering College 4

  • 8/3/2019 DBMSLabManual suresh

    5/34

    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 5

  • 8/3/2019 DBMSLabManual suresh

    6/34

    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 6

  • 8/3/2019 DBMSLabManual suresh

    7/34

    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 enterprisesoftware 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 canhold, and the complexity over the last 20 years.

    Oracle is one of the very widely used commercial RDBMS systems and at this point is themarket leader as far as RDBMS is concerned. Oracle9i is RDBMS software which supportsSQL 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 databaseserver level. Other popular DBMS software like Sybase and SQL Server support their ownprogramming extensions to SQL 1999.

    SPHOORTHY Engineering College 7

  • 8/3/2019 DBMSLabManual suresh

    8/34

    Department of MCA DBMS Lab Manual

    UNIT I (SQL)

    SQL (Structured Query Language) is a standard supported by all the popular relationaldatabase management systems in the market place. The basis data structure in RDBMS is atable. SQL provides you the features to define tables, define constraints on tables, queryfor 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 alterdata in RDBMS.

    Querying for Data:The typical syntax to query for data is;

    SELECT clauseFROM clauseWHERE 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, andaggregating functions.

    Get data in multiple rows grouped on an aggregating function applied on one ormore 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

  • 8/3/2019 DBMSLabManual suresh

    9/34

    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 fromtables.

    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 inthe 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 granularlevel.

    SQL 1999 is the standard which is supported by all commercial database vendors. If yourqueries are using SQL 1999 standard, they will run all RDBMS servers. In addition to theSQL 1999 standard, most commercial databases have their own extensions to SQLsupported 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 strongreason to go for additional features not included in SQL 1999 standard.

    SPHOORTHY Engineering College 9

  • 8/3/2019 DBMSLabManual suresh

    10/34

    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 aforeign key to employee table, department_id a foreign key to department table.

    Solution:4. Learn alter table syntax.

    SPHOORTHY Engineering College10

  • 8/3/2019 DBMSLabManual suresh

    11/34

    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 tableand 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 syntax3. 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 onedepartment_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 employee4. where should include condition on department_id

    SPHOORTHY Engineering College11

  • 8/3/2019 DBMSLabManual suresh

    12/34

    Department of MCA DBMS Lab Manual

    Experiment 7:

    Problem Statement:Select employee last_names from employee table who belong to a certain department_idand 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 fromemployee 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 employeetable 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 workingin the firm as of today.

    Solution:1. Use the select from where clause.

    SPHOORTHY Engineering College12

  • 8/3/2019 DBMSLabManual suresh

    13/34

    Department of MCA DBMS Lab Manual

    2. In the clause, get the current data using sysdate function, get the differencebetween sysdate and employee joining date and compute the days in betweenusing 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 ofemployee 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 querythat 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 inemployees table.

    Solution:1. Use select from where clause with the from coming from employee and departmenttables and a condition joining these two table using the foreign key department_id whichconnects both the tables with an equality condition.

    Experiment 14:

    SPHOORTHY Engineering College13

  • 8/3/2019 DBMSLabManual suresh

    14/34

    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 datacoming from the upper query. In this case, the salary and grade of each employeerow is used to execute the inner query to compare if there are any employees inthe 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 databy 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 havingclause.

    SPHOORTHY Engineering College14

  • 8/3/2019 DBMSLabManual suresh

    15/34

    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 gradeMANAGER.

    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 College15

  • 8/3/2019 DBMSLabManual suresh

    16/34

    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 usingnatural 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 anydepartment and departments that do not have any employees.

    4. Write a query to merge department level employee table data changes to collegelevel employee table on a periodic basis.

    5. I want to insert a lot of records in employee table which has certain constraints onsalary. I know all records I am inserting would be good in salary field. Tryinginserting as is and with the salary constraint disable before bulk insert and enableafter insert and see the time difference.

    6. Create index of salary column of employee and search for all employees with acertain salary.

    7. Instead of giving a unique ID yourself, what can be done to automatically generateunique ID.

    SPHOORTHY Engineering College16

  • 8/3/2019 DBMSLabManual suresh

    17/34

    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 proceduralunits of code.

    Benefits of PL/SQL:

    PL/SQL can improve the performance of an application. The benefits differ depending onthe execution environment:

    PL/SQL can be used to group SQL statements together within a single block and tosend the entire block to the server in a single call thereby reducing networkingtraffic. 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 higherperformance overhead. In a network environment, the overhead can becomesignificant.

    PL/SQL can also operate with Oracle server application development tools such asOracle forms and Oracle reports.

    PL/SQL Block Structure:

    Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separateor nested one within another. The basic units (procedures, functions, and anonymousblocks) 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 College17

  • 8/3/2019 DBMSLabManual suresh

    18/34

    Department of MCA DBMS Lab Manual

    Break down a complex problem into a set of manageable well defined logicalmodules and implement the modules with blocks.

    Place reusable PL/SQL code in libraries to be shared between Oracle forms andOracle reports, applications, or store it in a Oracle server to make it accessible toany 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 andprocedural 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 inthe 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-handlingroutines.

    PL/SQL Block Syntax:

    DECLARE [Optional]Variables, cursors, user defined exceptionsBEGIN [Mandatory]

    - SQL Statements - PL/SQL Statements

    Exception [Optional]-- Actions to be performed when errors occur ----

    END [Mandatory];

    Example:DECLARE

    v_variable VARCHAR2(5);BEGINSELECT column_nameINTO v_variableFROM table_name;

    EXCEPTIONWHEN exception_name THEN

    SPHOORTHY Engineering College18

  • 8/3/2019 DBMSLabManual suresh

    19/34

    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 result1WHEN expression2 THEN result2...WHEN expression THEN resultn[ELSE resultn1;]

    SPHOORTHY Engineering College19

  • 8/3/2019 DBMSLabManual suresh

    20/34

    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 LOOPStatement1;...END LOOP;

    Packages:

    Packages are collections of variables, user defined data types, procedures and functionswhich can either be either public or private. Packages are used to group related thingsinto one block that get loads into memory in one go. A package cannot be invokeddirectly.

    SPHOORTHY Engineering College20

  • 8/3/2019 DBMSLabManual suresh

    21/34

    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 withid = 5 and outputs that to standard output.

    Solution:1. Declare a varchar variable2. 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 ifthe value starts with S, in all smalls if it starts with R, and in initial capitals ifotherwise.

    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 isnot null and prints second value if first is null.

    Solution:

    SPHOORTHY Engineering College21

  • 8/3/2019 DBMSLabManual suresh

    22/34

    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 andoutputs that to standard output.

    Solution:3. Declare a varchar variable4. Write a LOOP.

    Experiment 24:

    Problem Statement:Write a PL/SQL block which updates 2 tables. If the second update fails the first updatealso 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 updatehas 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 College22

  • 8/3/2019 DBMSLabManual suresh

    23/34

    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 withid = 5. If there is no employee with id = 5 an error should be thrown. Otherwise the namehas 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 withid = 5. If the name has 8 characters, raise an exception called too many characters andhandle 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 tobe raised because the exception in fatal.

    Solution:1. As a part of exception handling, raise application error if the situation is notrecoverable.

    Experiment 30:

    Problem Statement:Create a stored procedure which takes deparment_id as parameter, inserts all employeesof that department in a table called dept_employee with the same structure.

    SPHOORTHY Engineering College23

  • 8/3/2019 DBMSLabManual suresh

    24/34

  • 8/3/2019 DBMSLabManual suresh

    25/34

    Department of MCA DBMS Lab Manual

    Unit II Additional Exercises

    1. Write a PL/SQL procedure which takes department id as parameter and gives allemployees 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, anexception 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 handleexceptions appropriately.

    SPHOORTHY Engineering College25

  • 8/3/2019 DBMSLabManual suresh

    26/34

    Department of MCA DBMS Lab Manual

    Unit III (Cursors & Triggers)

    Cursors:

    Every SQL statement executed by the Oracle server has an individual cursor associatedwith 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/QLblock.

    Controlling Explicit Cursors:

    o Declare the cursor by naming it and defining the structure of the query to be

    performed. Within it.

    SPHOORTHY Engineering College26

  • 8/3/2019 DBMSLabManual suresh

    27/34

    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 arenow 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 nowpossible 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 ONDECLAREV_empno employees.employee_id%TYPE;V_ename employees.last_name%TYPE;

    CURSOR emp_cursor ISSELECT employee_id, last_nameFROM employees;

    BEGINOPEN 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 LOOPCLOSE emp_cursor;

    Attributes of an Explicit Cursor:

    o %ISOPEN [is cursor open]

    SPHOORTHY Engineering College27

  • 8/3/2019 DBMSLabManual suresh

    28/34

    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 toapply 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 caneither 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 ordatabase.

    When should we use triggers?Triggers are to be used when we want to perform related actions and when we want tocentralize global operations. Create stored procedures and invoke them in a trigger, if thePL/SQL code is very lengthy. The excessive use of triggers can result in complexinterdependencies, which may be difficult to maintain in large applications. Triggersshould not be used where functionality needed is already built into the Oracle server orwhen 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 toenforce some rules on what should be the minimum salary.

    Elements in a Trigger:

    Trigger timingo 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 College28

  • 8/3/2019 DBMSLabManual suresh

    29/34

    Department of MCA DBMS Lab Manual

    allowed to complete. This situation enables you to eliminate unnecessary processing ofthe triggering statement and it eventual rollback in cases where an exception is raised inthe 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 aBEFORE trigger is already present.

    Instead of Triggers are used to provide a transparent way of modifying views thatcannot be modified directly through SQL DML statements because the view is notinherently modifiable. You can write INSERT, UPDATE, and DELETE statements against theview. The INSTEAD OF trigger works invisibly in the background performing the actioncoded in the trigger body directly on the underlying tables.

    Triggering user events:o INSERT

    o UPDATEo 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_nameTiming

    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 simplequery which is select from where using employee table and a condition department_id = 2

    SPHOORTHY Engineering College29

  • 8/3/2019 DBMSLabManual suresh

    30/34

    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 filehandles.

    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 closesthe 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 thejob 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 timein a log table whenever anyone attempts to change employees table.

    Solution:

    SPHOORTHY Engineering College30

  • 8/3/2019 DBMSLabManual suresh

    31/34

    Department of MCA DBMS Lab Manual

    1. We want to write a statement trigger that records the fact that someone is changingthe 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 withtime 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 theemployees table in a log table using after trigger that acts on insert, update and deleteoperations.

    Experiment 39:

    Problem Statement:Implement a solution that would record all attempted updates on salary in the employeetable along with the employee id, old salary, new salary and the time when it wasattempted 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 alongwith the employee id, old salary, new salary and the time when it was updated in anothertable.

    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 withmore than 20000 is revised.

    Solution:

    SPHOORTHY Engineering College31

  • 8/3/2019 DBMSLabManual suresh

    32/34

    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 aview but in reality the view is read-only and a trigger is updating the base tables based onthe 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/SQLblock.

    9. Write an after trigger which acts at a row level on insert/update/delete andtransfer old data to an audit trail table.

    SPHOORTHY Engineering College32

  • 8/3/2019 DBMSLabManual suresh

    33/34

    Department of MCA DBMS Lab Manual

    Supplementary Exercises

    1. Design a database for library management in the college, populate data and writequeries to return information like books issued, books issued to user, number ofbooks issued, books reserved, etc.

    2. Design a database for fee management in the college, populating data on feepayments, fee receipts and writing querying to return data like uncollected fees,

    which paid fee, etc.

    References

    Web-Sites:www.otn.oracle.com

    SPHOORTHY Engineering College33

    http://www.otn.oracle.com/http://www.otn.oracle.com/
  • 8/3/2019 DBMSLabManual suresh

    34/34

    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.