Course File - DBMS Lab Manual
Course File - DBMS Lab Manual
Course File - DBMS Lab Manual
SEMESTER : Third
Sr. Particular
No.
1 University-Vision and Mission
2 Department-Vision and Mission
3 PEO
4 PO
5 PSO
6 Course Objectives
7 Course Outcomes
8 Mapping of COs/POs/PSOs
9 Syllabus (As approved in BOS)---(If Any
Changes required, Approval Copy from DAA)
10 List of Experiments (Mapped with Cos)
11 Experiment 1…10
Aim
Objective
Input/Apparatus Used
Procedure/Algorithm/Code
Observations/Outcome
Discussion
Question: Viva Voce
Vision of the University
“To be globally recognized as a Centre of Excellence for Research, Innovation, Entrepreneurship and
disseminating knowledge by providing inspirational learning to produce professional leaders for serving
the society.”
M1: Providing world class infrastructure, renowned academicians and ideal environment for
Research, Innovation, Consultancy and Entrepreneurship relevant to the society.
M2: Offering programs & courses in consonance with National policies for nation building and
meeting global challenges.
M3: Designing Curriculum to match international standards, needs of Industry, civil society and for
inculcation of traits of Creative Thinking and Critical Analysis as well as Human and Ethical values.
M4: Ensuring students delight by meeting their aspirations through blended learning, corporate
mentoring, professional grooming, flexible curriculum and healthy atmosphere based on co-curricular
and extra-curricular activities.
M5: Creating a scientific, transparent and objective examination/evaluation system to ensure an ideal
certification.
M6: Establishing strategic relationships with leading National and International corporates and
universities for academic as well as research collaborations.
M7: Contributing for creation of healthy, vibrant and sustainable society by involving in Institutional
Social Responsibility (ISR) activities like rural development, welfare of senior citizens, women
empowerment, community service, health and hygiene awareness and environmental protection.
Vision of the Department
To be recognized as a leading Computer Science and Engineering department through effective teaching
practices and excellence in research and innovation for creating competent professionals with ethics,
values and entrepreneurial attitude to deliver service to society and to meet the current industry
standards at the global level.
M1: To provide practical knowledge using state-of-the-art technological support for the experiential
learning of our students.
M2: To provide industry recommended curriculum and transparent assessment for quality learning
experiences.
M3: To create global linkages for interdisciplinary collaborative learning and research.
M4: To nurture advanced learning platform for research and innovation for students‟ profound future
growth.
M5: To inculcate leadership qualities and strong ethical values through value based education.
PEO 1: To produce computer science graduate engineers with an ability to comprehend, understand and
analyze real life problems for providing sustainable solutions in the light of disruptive technologies.
PEO 2: To inculcate life-long learning skills in graduates preparing them for work in changing
environments and multidisciplinary teams in order to enhance their capability being globally
employable.
PEO 3: To instill leadership qualities in graduates with a sense of confidence, professionalism and
ethical attitude to produce professional leaders for serving the society.
PEO 4: To make the graduates adaptable to changing career opportunities who have the potential to
excel in industry/ public sector/ higher studies or entrepreneurship exhibiting global competitiveness.
PO2: Problem analysis: Identify, formulate, research literature, and analyze complex computer science
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex database and software
engineering problems and design system components or processes that meet the specified needs with
appropriate considerations for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of software engineering &networking based experiments, analysis and
Interpretation of data, and synthesis of the information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
Computer science engineering and IT tools including prediction and modelling to complex database or
software engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
social, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
Professional Computer Science & Engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional computer science
and engineering solutions in social and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development goals.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of computer science engineering practice
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO11: Project management and finance: Demonstrate knowledge and understanding of the computer
science engineering and management principles and apply these to one‟s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life- long learning in the broadest context of computer science engineering changes
PSO1. To acquire proficiency in developing and implementing efficient solutions using emerging
technologies, platforms and Free and Open-Source Software (FOSS).
PSO2. To gain critical understanding of hardware and software tools catering to the contemporary needs
of IT industry.
Student Outcomes (SOs)
CAC- SOs
SO1 Analyze a complex computing problem and to apply principles of computing and other relevant
disciplines to identify solutions.
SO2 Design, implement and evaluate a computing-based solution to meet a given set of computing
requirements in the context of the program‟s discipline.
SO4 Recognize professional responsibilities and make informed judgments in computing practice
based on legal and ethical principles.
SO5 Function effectively as a member or leader of a team engaged in activities appropriate to the
program‟s discipline.
SO6 Apply computer science theory and software development fundamentals to produce computing-
based solutions.
EAC- SOs
SO1 An ability to identify, formulate, and solve complex engineering problems by applying principles
of engineering, science, and mathematics
SO2 An ability to apply engineering design to produce solutions that meet specified needs with
consideration of public health, safety, and welfare, as well as global, cultural, social, environmental,
and economic factor
SO4 An ability to recognize ethical and professional responsibilities in engineering situations and make
informed judgments, which must consider the impact of engineering solutions in global, economic,
environmental, and societal context
SO5 An ability to function effectively on a team whose members together provide leadership, create a
collaborative and inclusive environment, establish goals, plan tasks, and meet objectives
SO6 An ability to develop and conduct appropriate experimentation, analyze and interpret data, and
use engineering judgment to draw conclusions
SO7 An ability to acquire and apply new knowledge as needed, using appropriate learning strategies.
Academic calendar
Syllabus
2 CourseCode- 3 0 2 4 5 CR
21CSH-214
Anti-requisite 21CST-251,21CST-252,21CSR-264
a. Course Description
The main DBMS course, we learn about the structural formation of data, maintain data integrity,
multitasking with concurrent access and recovery without occurring crashes, data structures, data models
etc. and their working in which every organization is based. At the end of the course, the students may
understand the concepts of data structures, data models and design, construction of queries by using
SQL, uses and applications of database design etc.
b. Course Objectives
1. To have good understanding of database system concepts and design databases for different
applications.
3. To implement and understand different types of DDL, DML and DCL statements.
c. Course Outcomes
CO1 Understand the database system concepts and design databases for different
applications.
CO2 Identify different types of DDL, DML, DCL and TCL commands and their usage.
techniques.
CO5 Evaluate database performance after implementing Triggers, procedures,
d. Syllabus
Unit I 15 Hours
Chapter 1.1 Overview of Databases: Database concepts, DBMS, Data Base System
Architecture (Three Level ANSI-SPARC Architecture), Advantages and
Disadvantages of DBMS, Data Independence, DBA and Responsibilities of
DBA, Relational Data Structure, Keys, Relations, Attributes, Schema and
Chapter 1.2 Data Models: Relational Model, Network Model, Hierarchical Model, ER
Model: Design, issues, Mapping constraints, ER diagram, Comparison of
Models.
capabilities.
Experiment 1.2 To explore “SELECT” clause using where, order by, between, like, group by,
having etc.
Experiment 1.3 Introduction and implementation of programs using Block Structure and
Variables.
Unit 2 15 Hours
Experiment 2.1 Introduction and implementation of programs using control structures If-
else statements and case statement.
Experiment 2.2 Introduction and implementation of programs using loops like: For, while,
Do-while.
Unit 3 15 Hours
Chapter 3.1 Package, Procedures and Triggers: Parts of procedures, Parameter modes,
Advantages of procedures, Syntax for creating triggers, Types of triggers,
package specification and package body, developing a package, Bodiless
Chapter 3.3 Database Recovery of database: Introduction, Need for Recovery, Types
e. Textbooks
2. Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to Design,
Implementation and Management”, 5/E, University of Paisley, Addison-Wesley.
Theory Practical
Components Internal Mid Term End Term Continuous Mid Term End Term
Assessment Assessment Assessment Assessment Assessment Assessment
Marks 20 40 60 40 20 40
quiz
Courses
questions)
Score on BB
h. CO-PO Mapping
CO1 3 - 2 3 - - - - - 3 - 3 3 -
CO2 3 - 2 3 - - - - - 3 - 3 3 -
CO3 3 3 2 2 - - - - - 2 - 2 2 -
CO4 3 3 2 2 - - - - - 3 - 1 2 -
CO5 3 3 3 2 - - - - - 3 - 3 3 2
S. No List of Experiments Mapped CO
UNIT-I
CO2
To implement different types of DDL, DML, DCL queries.
I.
II. To explore “SELECT” clause using where, order by, between, like, CO2
group by, having etc.
UNIT-II
CO5
Introduction and implementation of programs using Cursors.
VI.
VII.
UNIT-III
VIII. CO5
Introduction and implementation of programs of Procedures.
IX.
S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL
1. CREATE Command:
This command is used to create relations or tables. The column name must be specified along the data types.
Each table must have at least one column.
2. DESCRIBE Command:
It is use to describe the table. It includes information like table name, column name, data type etc.
3.INSERT Command:
Records can be added to table using this command. Only one row can be inserted at a time.
It is used to remove rows from a table. The entire row can be deleted using this command.
As shown here the row is deleted and table is shown in next figure.
6.ALTER Command
It is use to make changes in table. It can be used to add a new column or modify an existing one. It is also used
to delete a column.
Modification using alter command:
7.RENAME Command:
8.TRUNCATE Command
This command is used to remove all rows from the table and to release the storage space used by that table.
9.DROP Command
This command is used to remove the definition of a table. When you drop a table database loses all the data in
the table and all indexes associated with it.
10.UNION Command
It is used to combine the data of one or more columns of two tables with same data type.
Syntax: Select <column name> from<tablename1> union all Select <column name>
from<tablename2>;
11.MERGE Command
Name Type
Empno Number
Ename Varchar2(10)
Job Varchar2(10)
Mgr Number
Sal Number
Name Type
Deptno Number
Deptname Varchar2(10)
location Varchar2(10)
a. Add column designation to the department table.
Name Type
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER
c. List all employee names and their salaries, whose salary lies between 1500/- and 3500/- both inclusive.
d. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789.
Viva-Voce Questions
AIM: Implementation of select command with its variants like where, order by, between, like, group by
and having.
S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL
1. Where clause:
Where clause is used along with SELECT command to specify the condition based on which rows will be
extracted from table
2.Like Clause:
This operator is used for matching character patterns. The character pattern matching is called a wild card
search.
3.InClause:
4.BetweenClause:
It is used to specify a range of values. The range you specify contain lower and upper range.
Syntax:Select * from tablename where column name between value1 and value 2
5.Orderby clause:
It can be used to sort the rows. The clause sorts the query output according to the values in one or more
selected column.
It is used to check multiple condition if all conditions are true than output will be shown.
7.Or Clause:
It is used to check multiple condition if any one condition is true than output will be shown.
8.Groupby Clause:
It is used to collect data across multiple record and group the result by one or more columns.
Syntax:
Discussion
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)
b. What is the difference between maximum and minimum salaries of employees in the organization?
c. Display all employee names and salary whose salary is greater than minimum salary of the company and job
title starts with „M‟.
Q2. create table emp with attributes (eid number,ename varchar2(10),age number,salary number);
Q3. Consider the database for a college. Write the query for the following.
Ques 1 Mention the issues with traditional file-based systems that make DBMS a better choice
Ques 3 Are NULL values in a database the same as that of blank space or zero?
S/W Requirement: Oracle Database 11g Express Edition or oracle live SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90‟s to enhance the capabilities of SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in the client
system (client-side) or in the database (server-side).
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which are used
to manipulate data in the execution section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This
is a mandatory section and is the section where the program logic is written to perform any task. The
programmatic constructs like loops, conditional statement and SQL statements form the part of execution
section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates
gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly
with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested within
other PL/SQL blocks. Comments can be used to document code.
SQL> DECLARE
BEGIN
dbms_output.put_line(var);
END; /
Output:
Chandigarh University
Discussion
Ques2. Write a PL/SQL program to SWAP two numbers with and without using temporary variables.
Ques3. Write a PL/SQL program to print reverse of a number. For example: 1234 print as 4321.
S/W Requirement: Oracle Database 11g Express Edition or Oracle live SQL.
Introduction:
The IF statement executes a sequence of statements depending on the value of a condition. There are three
forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.
IF-THEN Statement
The simplest form of IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF (not ENDIF), as follows:
IF condition THEN
sequence_of_statements
END IF;
IF-THEN-ELSE Statement
The second form of IF statement adds the keyword ELSE followed by an alternative sequence of
statements, as follows:
IF condition THEN
sequence_of_statements1
ELSE
sequence_of_statements2
END IF;
IF-THEN-ELSIF Statement
Sometimes you want to select an action from several mutually exclusive alternatives. The third form
of IF statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:
IF condition1 THEN
sequence_of_statements1
ELSE
sequence_of_statements3
END IF;
For example:
DECLARE
bonus NUMBER(6,2);
emp_idNUMBER(6) := 120;
BEGIN
ELSE
bonus := 50;
ELSE
bonus := 0;
END IF;
END IF;
END;
The CASE statement in PL/SQL is similar to the IF-ELSEIF condition where different conditions are listed
within a block and only that statements get executed for which it satisfies the condition. CASE statement
matches the expression value instead of a Boolean expression. The expression could be of any data type
and the same data type has to be used in the statements. Each statement has a predefined value and if that
value matches up with the values passed in the selector expression then that particular statement gets
executed. In this topic, we are going to learn about the CASE statement in PL/SQL.
Syntax
Now that you have got a gist of what a CASE statement in PL/SQL is let‟s have a look at the syntax of the
CASE statement.
CASE (expression)
ELSE default_statement;
END CASE;
Code Explanation
In the syntax above, the expression will return a value of any data type, all the statements will have a
predefined unique value, the CASE expression will go through all the statements until it gets the exact
match defined in the value expression, in this case, Value_1, Value_2, and Value_3. If the Case expression
didn‟t find the match in the statement, then the default statement will get executed.
Note that the ELSE block is optional and if you do not want any default statement to get executed you can
skip this statement. The END Case is a mandatory part of the case.
Example
You could use the CASE statement in a SQL statement as follows: (includes the expression clause)
SELECT table_name,
CASE owner
END
FROM all_tables;
Or you could write the SQL statement using the CASE statement like this: (omits the expression clause)
SELECT table_name,
CASE
END
FROM all_tables;
The above two CASE statements are equivalent to the following IF-THEN-ELSE statement:
ELSE
END IF;
The CASE statement will compare each owner value, one by one.
One thing to note is that the ELSE clause within the CASE statement is optional. You could have omitted
it. Let's look at the SQL statement above with the ELSE clause omitted.
SELECT table_name,
CASE owner
END
FROM all_tables;
With the ELSE clause omitted, if no condition was found to be true, the CASE statement would return
NULL.
Discussion
Ques 1 Write a PL/SQL program to check whether a date falls on weekend i.e. SATURDAY or SUNDAY.
Ques 2 Write a PL/SQL program to display the description against a grade according to the marks achieved
by students in their final exams.
Ques 3 Write a PL/SQL program to identify whether a character entered by user is letter or digit.
S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL
A loop marks a sequence of statements that has to be repeated. The keyword loop has to be placed before the
first statement in the sequence of statements to be repeated, while the keyword end loop is placed immediately
after the last statement in the sequence.
Once a loop begins to execute, it will go on forever. Hence a conditional statement that controls the number of
times a loop is executed always accompanies loops.
Simple loop :
In simple loop, the key word loop should be placed before the first statement in the sequence and the keyword
end loop should be written at the end of the sequence to end the loop.
Syntax:
Loop
End loop;
Example:
DECLARE
inumber := 0;
BEGIN
LOOP
i:=i+1;
END LOOP;
END;
Output:
SQL>set serveroutput on
SQL>start d://it.sql
i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
WHILE loop
The while loop executes commands in its body as long as the condition remains true
Syntax :
LOOP
END LOOP
Example 1 :
DECLARE
numNumber(3) :=123;
ansNumber(3) :=0;
iNumber(3) :=0;
BEGIN
WHILE num != 0
LOOP
i:=mod(num,10);
ans:=(ans * 10 ) + i;
num:=floor(num/10);
END LOOP;
END;
Output :
SQL>set serveroutput on
SQL>start d://rev.sql
Example 2 :
BEGIN
WHILE n_counter<= 5
LOOP
n_counter := n_counter + 1
END LOOP;
END;
OUTPUT:
Counter : 1
Counter : 2
Counter : 3
Counter : 4
Counter : 5
The FOR loop can be used when the number of iterations to be executed are known.
Syntax :
LOOP
END LOOP;
The variable in the For Loop need not be declared. Also the increment value cannot be specified. The For
Loop variable is always incremented by 1.
Example 1 :
DECLARE
inumber ;
BEGIN
FOR i IN 1 .. 10
LOOP
dbms_output.put_line ('i = '||i);
END LOOP;
END;
Output :
SQL>set serveroutput on
SQL>start d://it.sql
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
Example 2 :
DECLARE
a number(2);
BEGIN
END loop;
END;
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
Discussion
Ques 1Write a program in PL/SQL to print the value of a variable inside and outside a loop using LOOP EXIT
statement.
Ques 2Write a program in PL/SQL to print 1st n numbers with a difference of 3 and starting from 1.
Ques 3Write a program in PL/SQL to insert records from one table to another.
Ques 3 What is the importance of %TYPE and %ROWTYPE data types in PL/SQL?
Experiment-VI:Introduction and implementation of programs of Cursors
S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL
Cursors
Oracle creates a memory area, known as context area, for processing an SQL statement, which
contains all information needed for processing the statement, for example, number of rows
processed etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors:
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement.
Attribute Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
Syntax
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example:
Opening the cursor allocates memory for the cursor, and makes it ready for fetching the rows
returned by the SQL statement into it. For example :
OPEN c_customers;
Closing the cursor means releasing the allocated memory. For example, we will close above
opened cursor as follows:
CLOSE c_customers;
EXAMPLE
Discussion
Ques 1Write a program in PL/SQL to find the number of rows effected by the use of
SQL%ROWCOUNT attributes of an implicit cursor.
Ques 3Write a program in PL/SQL to FETCH multiple records and more than one columns from
the same table.
VIEW
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
Employee table
View emp1
Discussion:
1. Write a query to create a view for those salesmen belonging to the city New York.
2. Write a query to create a view for all salesmen with columns salesman_id, name, and
city.
Write a query to create a view to getting a count of how many customers we have at each level
of a grade.
Salesman
-------------+------------+----------+------------
Customer
customer_id | cust_name | city | grade | salesman_id
-------------+----------------+------------+-------+-------------
Orders
Write a query to create a view that shows for each order the salesman and customer by
name.
Ques 2 What is the difference between a mutating table and a constraining table?
Procedure
A procedure or in simple a proc is a named PL/SQL block which performs one or more specific
task. This is similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.
IN - The parameter can be referenced by the procedure or function. The value of the parameter
cannot be overwritten by the procedure or function.
OUT - The parameter can not be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
Syntax
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
How to execute a Procedure?
procedure_name;
Example:
Ques 1 Write a procedure and call it into main pl/sql program to find a factorial of a number.
Ques 2 Create a procedure or function to calculate electricity bill as per the following criteria:
For first 100 units: Rs. 5 per unit
For 101-150 units: Rs. 7 per unit
For 151-300 units: Rs. 7.50 per unit
For 301 onward units: Rs. 8 per unit
Ques 3 Create Local procedure to calculate the simple interest by passing the values of principal,
rate and time.
Ques 2 Differentiate between the cursors declared in procedures and the cursors declared in the
package specifications.
Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.
Package specification
Package Specification
The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the package.
In other words, it contains all information about the content of the package, but excludes the
code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the
package specification but coded in the package body is called a private object.You can have
many global variables defined and multiple procedures or functions inside a package.
PROCEDURE find_sal(c_idcustomers.id%type);
END cust_sal;
When the above code is executed at the SQL prompt, it produces the following result −
Package created.
Package Body
The package body has the codes for various methods declared in the package specification and
other private declarations, which are hidden from the code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package created
above. I assumed that we already have CUSTOMERS table created in our database as mentioned
in the PL/SQL - Variables chapter.
PROCEDURE find_sal(c_idcustomers.id%TYPE) IS
c_salcustomers.salary%TYPE;
BEGIN
FROM customers
WHERE id = c_id;
END find_sal;
END cust_sal;
When the above code is executed at the SQL prompt, it produces the following result −
Packages
PROCEDURE addCustomer(c_idcustomers.id%type,
c_namecustomers.name%type,
c_agecustomers.age%type,
c_addrcustomers.address%type,
c_salcustomers.salary%type)
IS
BEGIN
ENDaddCustomer;
PROCEDURE delCustomer(c_idcustomers.id%type) IS
BEGIN
WHERE id =c_id;
ENDdelCustomer;
PROCEDURE listCustomer IS
CURSOR c_customersis
name_listc_list:=c_list();
BEGIN
name_list.extend;
name_list(counter):= n.name;
dbms_output.put_line('Customer('||counter||')'||name_list(counter));
END LOOP;
ENDlistCustomer;
ENDc_package;
Discussion
Triggers are simply stored procedures that are ran automatically by the database whenever some
event (usually a table update) happens. The trigger is mostly used for keeping the integrity of the
information on the database. For example, when a new record (representing a new worker) is
added to the employees table, new records should be created also in the tables of the taxes,
vacations, and salaries.
audit changes (e.g. keep a log of the users and roles involved in changes)
enhance changes (e.g. ensure that every change to a record is time-stamped by the
server's clock)
enforce business rules (e.g. require that every invoice have at least one line item)
execute business rules (e.g. notify a manager every time an employee's bank account
number changes)
replicate data (e.g. store a record of every change, to be shipped to another database later)
enhance performance (e.g. update the account balance after every detail transaction, for
faster queries)
The examples above are called Data Manipulation Language (DML) triggers because the triggers
are defined as part of the Data Manipulation Language and are executed at the time the data is
manipulated. Some systems also support non-data triggers, which fire in response to Data
Definition Language (DDL) events such as creating tables, or runtime or and events such as
logon, commit, and rollback. Such DDL triggers can be used for auditing purposes.
PL/SQL Triggers:-Triggers are basically PL/SQL procedures that are associated with tables,
and are calledwhenever a certain modification (event) occurs. The modification statements may
include INSERT, UPDATE, and DELETE.
TRIGGER trigger_name
BEFORE (or AFTER)
ON tablename
BEGIN
...
END;
TRIGGER specifies just what type of object we are creating. The BEFORE (or AFTER) in the
trigger definition refers to when you want to run the trigger, either before the actual database
modification (update, delete, insert) or after.
Permissions:-Just like with procedures and functions, creating triggers requires certain
privileges which are not part of the default privilege set. If you cannot create triggers from these
notes because of permissions, you (or the admin) has to GRANT CREATE TRIGGER privilege
on your username. For example, to allow user „alex‟ to create triggers, I may do something like
this:
Sample Table to be Triggered:-Before we begin playing with triggers, let‟s create a simple
table with which we can experiment:
Before Insert Trigger:-We write a trigger to fire before theinsert takes place.
CREATE OR REPLACE
TRIGGER PERSON_INSERT_BEFORE
BEFORE
INSERT
ON PERSON
BEGIN
DBMS_OUTPUT.PUT_LINE(‟BEFORE INSERT OF ‟ || :NEW.NAME);
END;
The single INSERT statement fires the trigger. When we run it, we get the print out of ‟BEFORE
INSERT OF JOHN DOE‟.
CREATE OR REPLACE
TRIGGER PERSON_INSERT_AFTER
AFTER
INSERT
ON PERSON
BEGIN
END;
Before Update Statement Trigger:-Now that we have some data in the table, we can create an
update trigger, that would firewhenever someone tries to update any person (or persons).
CREATE OR REPLACE
TRIGGER PERSON_UPDATE_S_BEFORE
BEFORE UPDATE
ON PERSON
BEGIN
END;
Trigger Exceptions:- Triggers become part of the transaction of a statement, which implies that
it causes (or raises) any exceptions (which we‟ll talk about later), the whole statement is rolled
back. Think of an exception as a flag that is raised when an error occurs. Sometimes, an error (or
exception) is raised for a good reason.
For example, to prevent some action that improperly modifies the database. Let‟s say that our
database should not allow anyone to modify their DOB (after the person is in the database, their
DOB is assumed to be static). Anyway, we can create a trigger that would prevent us from
updating the DOB:
CREATE OR REPLACE
TRIGGER PERSON_DOB
BEGIN
END;
ERROR at line 1:
You should also notice the error code of ORA-20000. This is our -20000 parameter.
Viewing Triggers:- You can see all your user defined triggers by doing a select statement on
USER_TRIGGERS.
For example:
Which produces the names of all triggers. You can also select more columns to get more detailed
trigger information.
Dropping Triggers:-You can DROP triggers just like anything. The general format would be
something like:
For example:-
Triggers
DECLARE
sal_diff number;
BEGIN
sal_diff:=:NEW.salary-:OLD.salary;
END;
Discussion
Ques 2 Implement trigger to delete student details from result table when he leaves the course.
Viva voce Questions
Ques 3 What are the virtual tables available during the execution of the database trigger?