DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... ·...

25
CODE: MIT/CSE/LM/05 CSE-212 RDBMS LAB MANUAL IV Sem, BE ( CS&E) ( 2009 scheme) Approved By: HOD

Transcript of DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... ·...

Page 1: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

CODE: MIT/CSE/LM/05

CSE-212 RDBMS LAB MANUAL

IV Sem, BE ( CS&E)

( 2009 scheme)

Approved By:

HOD Dept. of CS&E

DEPT OF COMPUTER SCIENCE & ENGG.

M. I. T., MANIPAL

Page 2: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

GENERAL INSTRUCTIONS TO STUDENTS

1. Students should be regular and come prepared for the lab practice.

2. In case a student misses a class, it is his/her responsibility to complete that missed experiment(s).

3. Students should bring the observation book, lab journal and lab manual. Prescribed textbook and class notes can be kept ready for reference if required.

4. They should implement the given experiment individually.

5. While conducting the experiments students should see that their programs would meet the following criteria:

Programs should be interactive with appropriate prompt messages, error messages if any, and descriptive messages for outputs.

Programs should perform input validation (Data type, range error, etc.) and give appropriate error messages and suggest corrective actions.

Comments should be used to give the statement of the problem and every function should indicate the purpose of the function, inputs and outputs

Statements within the program should be properly indented 4Use meaningful names for variables and functions. Make use of Constants and type definitions wherever needed.

6. Once the experiment(s) get executed, they should show the program and results to the instructors and copy the same in their observation book.

7. Questions for lab tests and exam need not necessarily be limited to the questions in the manual, but could involve some variations and / or combinations of the questions.

Note: Above mentioned instructions can be modified based on the context of the lab.

Page 3: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

CONTENTS

SL NO. TITLE OF EXPERIMENT WEEKS

1. MSACCESS 1 week

2. SQL 6 weeks

3. PL/SQL BASICS programs 1 week

4. Cursors & exception handling 2 weeks

5. Procedures, Functions, 2 weeks

6. Test 2 weeks

12 weeks

PROCEDURE OF EVALUATION

Student will be evaluated based on the following criteria:

Implementation of experiments, Observation and /or 60%(60 Marks)JournalAndViva

Test 40% (40 Marks)

Page 4: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

1. MSACCESS

1. Creating Tables2. Forms 3. Relationships4. Filters 5. Queries6. Reports7. SQL

Exercises:

1. Create four tables for the VideoParlour database using Design view. The tables are Member to hold members details, Video to hold details of videos, VideoForRent to hold the details of copies of videos for rent, and RentalAgreement to hold the details of video rentals by members.

The Member table has the following fields (with the data type of each in brackets):memberNo (AutoNumber), fName (Text), lName (Text), sex (Text), DOB (Date/Time), address (Text), dateJoined (Date/Time), comments (Memo)The primary key is memberNo.(Also for this table, set the format property of the Sex field to a field size of 1 with an Input Mask >L. Also, set this field with a Validation Rule =”M” or “F” and Validation Text Please enter M or F. If you do not understand the purpose of the properties associated with each field, Use the help facility using the F1 key).

The Video table has the following fields (with the data type of each in brackets):catalogNo (Text), title (Text), category (Text), dailyRental (Currency), price (Currency), directorNo (Text).The primary key is catalogNo

The VideoForRent table has the following fields (with the data type of each in brackets): videoNo (Text), available (Yes/No), catalogNo (Text)The primary key is videoNo

The RentalAgreement table has the following fields (with the data type of each in brackets): rentalNo (AutoNumber), dateOut (Date/Time), dateReturn (Date/Time), memberNo (Text), videoNo(Text)The primary key is rentalNo(Also for this table, set the format property for the dateOut and dateReturn fields to Medium Date format e.g. 10-Oct-00.)

2. Open your VideoParlour database. Create a form for your Video table using the Form Wizard facility and name this form VideoForm1. Use the form to view records in your Video table. Practise, changing between viewing your Video table using Form view and Datasheet view.

3. Create relationships between your Member, RentalAgreement, VideoForRent, Video tables using the Relationship window.

Page 5: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

4. Apply filters to the members and video records. For example, create the following filters to view:

Only male members of the video shop. Only male members of the shop who joined the shop this year in order of last

name and then first name. All members born in the 1960s. Only videos in the Children category with a daily rental rate of less than £4.00

and sorted according to video title. Only videos currently available for rent with a certification of “PG” or “U”. Only videos by a certain director.

5. Using the Select Query window, select your Member, RentalAgreement, VideoForRent, Video tables. Practise, joining and deleting the join lines between your tables. Examine the join properties of the join lines relating your tables.

6. Create a report for your Video table containing the catalogNo, title, category and certificate fields. Group your records according to the values in the category field and then sort on the values in the title field.

Create a report for your Video table containing the category, dailyRental and price fields. Group your records according to the values in the category field and then sum the values in the dailyRental and price fields.

Create a report based on a query that contains the following fields memberNo, fName, lName, videoNo, title, dateOut and dateReturn. Group your records according to memberNo and then order by videoNo.

7. Using Access SQL, create simple select queries on the tables of your StayHome database. For example, create and save the following queries on the Video table.

List the catalogNo, title and category of the Video table, ordered by video title List title, certificate, category and dailyRental of the Video table for videos in the

“Childrens” category with a rental rate less than £4.00. List all videos with a certification of “PG” or “18”in the Video table.

2. SQL

2.1 Try the following SQL plus commands:Creating a Table CREATE TABLE <tableName> (<list of attributes and their types>);Creating a Table with a Primary KeyCREATE TABLE <tableName> (<attribute_name> <type> PRIMARY KEY,);CREATE TABLE <tableName> (<attrs and their types>, PRIMARY KEY (<attribute1>, <attribute2>));Inserting TuplesINSERT INTO <tableName> VALUES (<list of values for attributes, in order>);Deleting TuplesDELETE FROM <tableName> [where <condition>];Updating Column values

Page 6: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

UPDATE <tableName> SET <columnName = value>;Getting the Value of a RelationSELECT * FROM <tableName>;SELECT Column1, column2, … from <tableName>;Modifying the structure of TablesAdding New Columns:ALTER TABLE <tableName> ADD COLUMN(<newColumnName> <dataType(size)>, …);Change size of existing columns://ALTER TABLE <tableName>ALTER(<ColumnName>TYPE<newDataType(newSize)>, …);

Restrictions: Changing the name of table

ALTER TABLE <tablename> RENAME TO <Newname> Changing the name of the column

ALTER TABLE <tablename> RENAME COLUMN <old column name> TO <new column name>

Getting Rid of Your Tables and attributesDROP TABLE <tableName>;ALTER TABLE <table name> DROP (<column>)

PgSQL DataypesIntegerCharfloat

2.2 Creating, Updating and Querying the Tables.

Create the students table:

students ( RollNo(integet) , name (gvarchar),hostel INTEGER, cgpa NUMERIC(3,2) )(or float);

Run the following queries :

-- SELECT * FROM students;SELECT rollno FROM students;

-- SELECT rollno, name FROM students WHERE cgpa > 9.00;

Updates/deletes:

RollNo Name HostelNoSize cgpa‘99305017’ ‘Sai Sundar’ 11 7.23‘99305018 ‘Shyam Sundar’ 11 9.23‘99305019’ ‘Ram Sundar’ 12 8.32

Page 7: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

-- UPDATE students SET cgpa = 9.46 WHERE rollno = '99305018'; -- DELETE students WHERE rollno = '99305018';

Multitable queries: CREATE TABLE course ( courseno CHARACTER(8), coursename VARCHAR(30)); CREATE TABLE registered ( rollno CHARACTER(8), courseno CHARACTER(8));

Query to find all course numbers with students from Hostel 11

SELECT courseno FROM students, registered WHERE students.rollno = registered.rollno AND students.hostel = 11(Course numbers may appear multiple times: use SELECT DISTINCT instead of SELECT to get them only once.)

Try some more queries: -- course numbers with some students with cgpa < 6 -- rollnumbers of all students registered for course CS317

2.3 Implement the Bank Database and execute the given queries/updates

Bank Database Schema:

account(account_number, branch_name, balance)branch (branch_name, branch_city, assets)customer (customer_name customer_street, customer_city)loan (loan_number, branch_name, amount) depositor((customer_name, account_number)borrower(customer_name, loan_number)

Note: Use BankDB.sql to create and populate the Database

Queries/Updations on Bank Database

Retrieving records from a table:

1. List all branch names and their assests2. List all accounts of Brooklyn branch3. List all loans with amount > 1000.4. List all accounts of Perryridge branch with balance < 1000.5. List Numbers of accounts with balances between 700 and 900

Updating records from a table:6. Change the assests of Perryridge branch to 340000000.7. Transfer the accounts and loans of Perryridge branch to Downtown branch.8. Transfer Rs. 100 from account A-101 to A-215.

Deleting records from a table:9. Delete the branch Perryridge. 10. Waive off all the loans with amount < 1000.11. Delete the accounts and loans of Downtown branch.

Modifying the structure of tables:12. Add a column phoneNo to customer table.

Page 8: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

13. Change the size of the branch_city to varchar(20).14. Drop the column phoneNo from customer table.

Retrieving records from multiple tables15. For all customers who have a loan from the bank, find their names, loan numbers, and loan amount.16. Find the customer names, loan numbers, and loan amounts, for all loans at the Perryridge branch. Rename and Tuple Variables(Use as in select and from) 17. For all customers who have a loan from the bank, find their names and loan numbers with the attribute loan_number replaced by loan_id.18. Find the names of all branches that have assets greater than atleast one branch located in Brooklyn.

String Operations (Use %, _, LIKE)19. Find the names of all customers whose street address includes the substring ‘Main’.

Ordering the display of Tuples(Use ORDER BY ASC DESC)20. List loan data, ordered by decreasing amounts, then increasing loan numbers.

3. SQL (Continued…)

Implement the following Queries on Bank Database:

3.1 Set OperationsUNION (Use union all to retain duplicates):21. Find all the bank customers having a loan, an account, or both at the bank.

INTERSECT (Use intersect all to retain duplicates):22. Find all the bank customers having both a loan and an account at the bank

EXCEPT(Minus):23. Find all customers who have an account but no loan at the bank.

3.2 Aggregate Functions (avg,min,max,sum,count) / Group By24. Find the average account balance at the Perryridge branch.25. Find the average account balance at each branch.26. Find the number of depositors for each branch (Use distinct).27. Find those branches where the average accounts balance is more than Rs. 1200.28. Find the number of branches of the bank.29. Find the average balance for each customer who lives in Harrison and has at least three accounts.

3.3 Null values30. Find all loan numbers that appear in the loan relation with null values for amount.

3.4 Nested Subqueries

Set Membership (in / not in):31. Find all the customers who have both a loan and an account at the Perryridge branch

Page 9: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

32. Find all customers who do have a loan at the bank, but do not have an account at the bank.33. Select the names of customers who have a loan at the bank, and whose names are neither Smith nor Jones

Set Comparison (>some/all):34. Find the names of all branches that have assets greater than those of at least one branch located in Brooklyn.35. Find the names of all branches that have an asset value greater than that of each branch in Brooklyn.

Test for Empty Relations (exists/ not exists):36. Find all customers who have both an account and a loan at the bank37. Find all customers who have an account at all the branches located in Brooklyn. Test for Absence of Duplicate Tuples38. Find all customers who have at most one account at the Perryridge branch39 Find all customers who have at least two accounts at the perryridge branch

3.5 Complex queriesDerived Relations40. Find the average account balance of those branches where the account balance is greater than Rs. 1200.41. Find the maximum across all branches of the total balance at each branch

With Clause42. Select the accounts with maximum balance.

43. Find all branches where the total account deposit is greater than the average of the total account deposits at all branches.

3.6 Views44. Create a view all_customers consisting branches and their customers.45. Select all the customers from all_customers view.46. Create a view Perryridge_customers consisting customers of Perryridge branch using all_customers view.

3.7 Modification of the Database(Use ROLLBACK (and SAVEPOINT) to undo the effect of any modification on database before COMMIT)47. Delete all loans with loan amounts between Rs. 1300 and Rs, 1500.48. Delete all account tuples at every branch located in Brooklyn.49. Present a new Rs. 200 savings account as a gift to all loan customers of Perryridge branch(Note: It requires insert into account and depositor). 50. Pay 5% interest to all accounts with a balance of Rs. 1000 or more.51. Pay 5% interest on accounts whose balance is greater than average52. Pay 6% interest on accounts with balances over Rs. 10000 whereas pay 5% interest on all other accounts (use case).

4. SQL (Continued…)

4.1 Integrity Constraints

Page 10: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

Ensure the uniqueness of the primary key(PRIMARY KEY) column_name data_type primary key Primary key(column_name(s))

Ensure the uniqueness of the candidate key which is not the primary key column_name data_type unique

Ensure that child records in related tables have a parent record.

foreign key(column_name) references table_name(column_name)

Delete child records when the parent record is deleted. foreign key(column_name) references table_name(column_name) on delete cascade

Ensure that columns always contain a value. column_name data_type not null

Ensure that a column contains a value within a set/specific range. check (column_name in (value1, value2,..)) check (predicate)

Ensure that a default value is placed in a column. column_name data_type default (value)

Consider the following schema: Employee (EmpNo, EmpName, Sex, Salary, Address, DNo) Department (DeptNo, DeptName, Location)

1. Create Employee table with following constraints: Make EmpNo as Primary key Do not allow EmpName, Sex, Salary and Address to have null values Allow Sex to have one of the two values: ‘M’, ‘F’ Set the default salary value to Rs. 1000.

2. Create Department table with following: Make DeptNo as Primary key Make DeptName as candidate key

3. Make DNo of Employee as foreign key which refers to DeptNo of Department

[ Note: To view the name of integrity constraintsSELECTCONSTRAINT_NAME, CONSTARINT_TYPE, FROM USER_CONSTRAINTSWHERE TABLE_NAME=’Employee’; ]

4. Insert few tuples into Employee and Department which satisfies the above constraints

Page 11: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

5. Insert few tuples into Employee and Department which violates some of the above constraints

6. Modify / Delete a tuple which violates a constraint (e.g. drop a department tuple which has one or more employees)

7. Modify the foreign key constraint of Employee table such that whenever a department tuple is deleted, the employees belonging to that department will also be deleted

4.2 Naming Constraints Oracle constraint name is SYS_Cn, where n is a numeric value Constraints can have unique user defined name as given below:

CONSTRAINT <constraint_name> <constraint_definition>e.g. constraint account_pk primary key(account_number)

Modifying Constraints:ALTER TABLE <table_name>

ADD / MODIFY/DROP/DISABLE/ENABLE/VALIDATE/NOVALIDATE CONSTRAINT <constraint_name>

8. Repeat some of the examples (1 to 7) with named constraints. 9. Try some more examples with ADD, DROP, DISABLE, ENABLE, VALIDATE INVALIDATE and NOVALIDATE

4.3 Built-in Functions (Use Bank Database for the exercise problems given below)

LENGTH(string)10. List the customer names along with the length of the customer names

LOWER(string)11. List the customer names in lower case

SUBSTR(string, start, count) 12. List the customer names and 3 characters from 3rd position of each customer name

UPPER(string)13. List the customer names in upper case

NVL(column_name, substitute value)14. Replace NULL with value1(say 0) for a column in any of the table ROUND(value, precision)15. List the balance and balance/3 rounded to nearest hundred from account

(Add data of birth column DOB to Employee Table. Insert appropriate DOB values for different employees and try the exercise problems given below) TO_CHAR(date1, format)16. Display the birth date of all the employees in the following format:

Page 12: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

‘DD-MON-YYYY’ ‘DD-MON-YY’ ‘DD-MM-YY’

17. List the employee names and the year(fully spelled out) in which they born ‘YEAR’ ‘Year’ ‘year’

18. List the employee names and the day(of the week fully spelled out) in which they born

‘DAY’ ‘Day’

19. List the employee names and the month(fully spelled out) in which they born ‘MONTH’ ‘Month’

LAST_DAY(date1)20. Find the last day of the month(and its day of the week) in which employee Mr. X is

born

MONTHS_BETWEEN(date1, date2)21. Find the age of all the employees

[Hint: Use SYSDATE]

NEXT_DAY(date1, ‘day’) ADD_MONTHS(date1, number of months)22. Find the Saturday following the Employee’s 60th birthday

TO_DATE(string, ‘format’)e.g. to_date(‘12021998’, ‘DDMMYYYY’)

23. List the employees whose birth day falls in the given year X24. List the employees whose birth day fall between the given years X and Y25. List the employees who will retire on the given year X. [Hint: use & with the variable name (e.g. &X) in the SQL query to read the value from the user]

5. SQL(Continued…)

Implement the Hospital Database and execute the given queries:

Relations (Include all the necessary integrity constraints):BILLEDBILL NO NUMBER(5) - PRI KEYPATIENT_NO NUMBER(9) 

Page 13: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

ITEM_CODE  NUMBER(5)CHARGE NUMBER(7,2)

TREATSPHY_ID NUMBER(4) - PRI KEYPATIENT_NO NUMBER(4) - PRI KEYPROCEDURE_NO NUMBER(4) - PRI KEYDATE_TREATED DATE - PRI KEYTREAT_RESULT VARCHAR2(50)

ITEMITEM_CODE NUMBER(4) - PRI KEYDESCRIPTION VARCHAR2(50)NORMAL_CHARGE NUMBER(7,2)

PHYSICIANSPHY_ID NUMBER(4) - PRI KEYPHY_PHONE CHAR(8)PHY_NAME VARCHAR2(50)

PATIENTPATIENT_NO NUMBER(4) - PRI KEYDATE_ADMITTED DATEDATE_DISCHARAGED DATEPAT_NAME VARCHAR2(50)ROOM_LOCATION CHAR(4)

ROOMROOM_LOCATION CHAR(4) - PRI KEYROOM_ACCOMODATION CHAR(2)ROOM_EXTENSION NUMBER(4)

PROCEDURESPROCEDURE_NO NUMBER(4) - PRI KEYPROC_DESCRIPTION VARCHAR2(50)

Implement the following queries (Use Hospital_DB.sql to populate the DB):

1. Get the PATIENT_NO, ITEM_CODE, and CHARGE and from the BILLED table for a specific PATIENT_NO

2. List all of the different charges that are stored to the table3. Display all columns and all rows from the BILLED table4. Display all charges greater than Rs. 5.00 for the PATIENT_NO 11165. Display all charges for either patient 1116 or patient 11176. Count the number of times patient 1116 has been charged for items

Page 14: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

7. Display number of DISTINCT procedures performed on a patient8. Give a meaningful column name for number of DISTINCT procedures in the

above query9. Display a calculated value such as the current charge and the amount that would

be charged if the charge were increased by 6% for all rows in the ITEM table10. List all patients hospitalized more than 6 days11. List the total charges per patient for expensive medical items (CHARGE greater

than Rs100 for an item) where patients owe the hospital a  sum (total charges over Rs500)

12. List the patients who had either Dr. Hawkeye Pierce or Dr. Trapper John or Dr. Jonas Salkman as a physician

13. Show the patient names (PAT_NAME field) and associated physician names (PHY_NAME field) along with the Patient information

14. List the PATIENT_NO and DATE_DISCHARGED from the PATIENT table and the associated CHARGE from the BILLED table.

6. PL/SQL

1. PL/SQL Environment 2. PL/SQL Syntax3. Conditional & iteration control: IF-THEN – END IF

WHILE LOOP Exercise

Usage of IF –THEN

Write a PL/SQL code block that will accept an account number from the user and debit an amount of Rs. 2000 from the account if the account has a minimum balance of 500 after the amount is debited. The Process is to fired on the Accounts table.

Usage of While:

Write a PL/SQL code block to calculate the area of the circle for a value of radius varying from 3 to 7. Store the radius and the corresponding values of calculated area in a table Areas.

Areas – radius, area.

Usage of For:

Write a PL/SQL block of code for inverting a number 5639 or 9365.

Usage of for and goto Statement:

Write a PL/SQL block of code to achieve the following: if the price of Product ‘p00001’ is less than 4000, then change the price to 4000. The Price change s to be recorded in the

Page 15: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

old_price_table along with Product_no and the date on which the price was last changed. Tables involved: product_master- product_no, sell_price.

Old_price_table- product_no,date_change, Old_price

7. Exceptions and Cursors

-Exception handling-Use of cursors -Types of cursors –Implicit & Explicit -Opening a cursor -Explicit cursor attributes.-Cursor for loops

Exercise:

Error Handling:

Write a Pl/Sql block which displays area for a given radius. If no data found then display an error message.

Modify the above problem to demonstrate too_many_values and others exception

Write a PL/SQL block of code such that depending upon the user entered salesman_no, the commission_amount is calculated and inserted into the commission_payable table. Salesman_Master (salesman_no, salesman_name, rate_of_commission, tgt_to_get, ytd_sales) table records the sales informationof different salesperson. A salesman is eligible for commission only when he achieves the target sales when omission is paid. The commission amount, the salesman_no and the date_of_payment is recorded in commission_payable table. Raise an exception if the total sales by a salesman is less than the target.

Cursors:Employee –Emp_code, Emp_name, job, salary, Dept_no.

CursorName %ISOPEN / %FOUND / %NOTFOUND:The HRD manager has decided to raise the salary for all the employees in department number 20 by 0.05. whenever any such raise is given to the employees, a record for the same is maintained in the temp_raise table. It includes the employee number, the date when the raise was given and the actual raise. Write a PL/SQL block to update the salary of each employee and insert a record in the emp_raise table.

CursorName%ROWCOUNT:

Write a PL/SQL block that will display the name, department and salary of the first 10 employees getting the highest salary.

Page 16: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

8. Additional Constructs in Cursors

Exercise:

A HRD manager has decided to raise the salary for all the employees in Department number 20 by 0.05. Whenever any such raise is given to the Employees, an audit trail of the same are maintained in the emp_raise table. The emp_raise table holds the employee number the date when the raise was given and the raise amount. Write a PL/SQL block to update the Salary of each employee of dept_no 20 appropriately and insert a record in the emp_raise table as well.

Employee- Emp_code, Ename, Dept_no, job, salary.Emp_raise-Emp_code, Raise_date, Raise_amt.

Cursor For Loops:

Repeat the above problem using cursor for loops.

Where Current of:

Repeat the above problem using where current of.

Parameterized Cursors:

Write a Pl/Sql block of code that would update the Bal_stock in the item_master(Itemid, Description, Bal_stock) table each time a transaction takes place in the item_transaction (Itemid, Description, Quantity) table. The change in the item_master table depends on the itemid. If the itemid is already present in the item_master table then an update operation is performed to decrease the Bal_stock by the Quantity specified in the item_transaction table. In case the itemid is not present in the item_master table then the record is inserted into the item_master table.

Transactions: COMMIT / ROLLBACK / SAVEPOINT:

Write a Pl/Sql block first inserts a record in the Emp(Emp_No,Emp_Name,Sal) in ‘Emp’ table. Update the salaries of Anand and Mohan by Rs. 2000 and Rs.1500 respectively. Then check to see that the total salary does not exceed 20000. if the total salary is greater than 20000 then undo the updates made to the salaries of Anand and Mohan.

9. Triggers:

- Row Triggers, statement Triggers, Before Vs After Triggers, - Execute, Modify, Drop, disable, and Enable Triggers commands. - SHOW ERRORS. - RAISE_APPLICATION_ERROR.

Page 17: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

Exercise:

Write a row trigger to insert the existing values of the salary table into a new table when the salary table is updated

Write a row trigger to update the ITMStock in ITMMAST when a new transaction is occurred.

Create a transparent audit system for a table Client_master (client_no, name, address, Bal_due). The system must keep track of the records that are being deleted or updated. The functionality being when a record is deleted or modified the original record details and the date of operation are stored in the auditclient(client_no, name, bal_due, operation, userid, opdate) table, then the delete or update is allowed to go through.

10. Procedures, Functions& Packages:

Parameter modes- IN, OUT, IN OUT

Exercise:

Procedures:

Write a simple procedure to display a message “Good Day to You”

Write a procedure which takes the department_id as input parameter and lists the names of all employees belonging to that department.

Write a Pl/Sql block of code that lists the highest salary drawn by an employee in each of the departments. It should make use of a named procedure dept_highest which finds the highest salary drawn by an employee for the given department.

Code a procedure to calculate the sales made to a particular Customer. (The customer id in the transaction file must be Selected, the quantity sold must be multiplied by the price Which is in the ITEM master and this value must be Accumulated for all records of that customer in the Transaction file).

Use movies database: (a) Create procedure to find out mv_no issued to IVAN (b) Create procedure to find out names and mv_no of all customers who have been issued a movie (c) Create title and type of movies that have been issued to 'Vandana'

Functions:

Code a function to return the Square of a given number.

Code a function to return the net salary given the employee number.

Page 18: DBMS LAB MANUAL FOR IV SEM B - Mitfilesresource.mitfiles.com/CSE/II year/IV sem/RDBMS - LAB... · Web viewStudents should bring the observation book, lab journal and lab manual. Prescribed

Write a Pl/Sql block of code that lists the highest salary drawn by an employee in each of the departments. It should make use of a function dept_highest which return the highest salary drawn by an employee for the given department.

13&14. Test

References:

1. Ivan Bayross, “SQL, PL/SQL” 2nd / 3rd Edition , BPB Publications

******************