0% found this document useful (0 votes)
9 views55 pages

Advance Database Management System Laboratory (B)

The document outlines various programs related to Advanced Database Management Systems, including database design using E-R models, implementation of DDL commands for table management, and constraints such as primary and foreign keys. It also covers DML commands for data manipulation, DCL commands for permission management, and built-in SQL functions. Additionally, it discusses nested queries and join queries, providing syntax and examples for each concept.

Uploaded by

latovi7698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views55 pages

Advance Database Management System Laboratory (B)

The document outlines various programs related to Advanced Database Management Systems, including database design using E-R models, implementation of DDL commands for table management, and constraints such as primary and foreign keys. It also covers DML commands for data manipulation, DCL commands for permission management, and built-in SQL functions. Additionally, it discusses nested queries and join queries, providing syntax and examples for each concept.

Uploaded by

latovi7698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Advanced Database Management System laboratory

Program-1: Database design using E-R model and Normalization


a) Construct an E-R diagram that models exams as entities, and uses a ternary
relationship, for the database (a database used to record the marks that students get in
different exams of different course offerings)
E-R Model:- An ER diagram shows the relationship among entity sets. An entity set is a
group of similar entities and these entities can have attributes. In terms of DBMS, an entity is
a table or attribute of a table in database, so by showing relationship among tables and their
attributes, ER diagram shows the complete logical structure of a database. Let’s have a look
at a simple ER diagram to understand this concept.
Here are the geometric shapes and their meaning in an E-R Diagram. We will discuss these
terms in detail in the next section(Components of a ER Diagram) of this guide so don’t worry
too much about these terms now, just go through them once.

Rectangle: Represents Entity sets.


Ellipses: Attributes
Diamonds: Relationship Set
Lines: They link attributes to Entity Sets and Entity sets to Relationship Set
Double Ellipses: Multivalued Attributes
Dashed Ellipses: Derived Attributes
Double Rectangles: Weak Entity Sets
Double Lines: Total participation of an entity in a relationship set

Draw an ER diagram for university database consisting of four entities

1. Student
2. Department
3. Class
4. Faculty and convert into tables

• A student has a unique id and can enroll for multiple classes and has at most one
major
• Faculty must belong to department and faculty can take multiple classes

Page |1
Advanced Database Management System laboratory

• Every student will get a grade for the class for he/she was enrolled

Degree:-
The degree of a relationship is the number of entity types that participate in the relationship.
The three most common relationships in ER models are Binary, Unary and Ternary
• A unary relationship is when both participants in the relationship are the same entity.

• A binary relationship is when two entities participate, and is the most common
relationship degree.

• A ternary relationship is when three entities participate in the relationship.

Page |2
Advanced Database Management System laboratory

Example-1: Consider a Mobile manufacture company.

Three different entities involved:

• Mobile - Manufactured by company.


• Part - Mobile Part which company get from Supplier.
• Supplier - Supplier supplies Mobile parts to Company.

Mobile, Part and Supplier will participate simultaneously in a relationship. because of this
fact when we consider cardinality we need to consider it in the context of two entities
simultaneously relative to third entity.

Example-2: The University might need to record which teachers taught which subjects
in which courses.

Page |3
Advanced Database Management System laboratory

Example-3: Construct an E-R diagram that models exams as entities, and uses a ternary
relationship.

Page |4
Advanced Database Management System laboratory

Program-2 Implementation of DDL commands to perform creation of


table, alter , modify and drop column operation.

DDL :
DDL Stands for "Data Definition Language." A DDL is a language used to define data
structures and modify data.
For example, DDL commands can be used to add, remove, or modify tables within in
a database. DDLs used in database applications are considered a subset of SQL, the
Structured Query Language. However, a DDL may also define other types of data, such
as XML.
A Data Definition Language has a pre-defined syntax for describing data. For example, to
build a new table using SQL syntax, the CREATE command is used, followed by parameters
for the table name and column definitions. The DDL can also define the name of each
column and the associated data type. Once a table is created, it can be modified using the
ALTER command. If the table is no longer needed, the DROP command can be used to
delete the table.

COMMAND DESCRIPTION
CREATE Is used to create the database or its objects (like table, index,
function, views, store procedure and triggers)
DROP is used to delete objects from the database.
ALTER is used to alter the structure of the database.

CREATE TABLE AND INSERT VALUES INTO TABLE

Create Table:-

In any RDBMS, tables are basic unit of data storage. Tables holds all of the user-
accessible data.

To create a table, it is necessary to name the table and all the attributes that
compose it. In addition, for every attribute, the user needs to define its data type
and, if necessary, the appropriate constraint or constraints. The name of table
identifies it as a unique object within the RDBMS.

Page |5
Advanced Database Management System laboratory

Columns and attribute name serve to differentiate the attributes from one another.
The Data type of each attribute defines the characteristics of its underlying domain.

CREATE TABLE command is used to define (Create) a table.

Syntax of CREATE TABLE command is:-

CREATE TABLE<table_name>

(<column_specification>,<column_specification> …..);

Where <table_name> gives the table name and <column_specification> includes

• Column name
• Data type
• Length of column, if any
• Constraints, if applicable

Example:-

CREATE TABLE EMPLOYEE

E_CODE CHAR(4),

NAME CHAR(30),

Page |6
Advanced Database Management System laboratory

SEX CHAR(1),

PHONE INT,

SALARY DECIMAL (18,2));

This will create the EMPLOYEE table with five columns namely
E_CODE,NAME,SEX, PHONE,SALARY.

This will create the EMPLOYEE table with all the following constraints:

• E_CODE is an attribute of type character.


• NAME is an attribute of type character.
• SEX is an attribute of type character.
• PHONE is an attribute of type integer.
• SALARY is an attribute of type decimal.

ALTER COMMAND

➢ To Add column in existing table:-

We can alter the structure of the table using ALTER TABLE statement, once the table is
being created. The ALTER TABLE statement helps the designer to make necessary
changes to the existing table instead of creating the table from the scratch.

Now we shall discuss how the ALTER TABLE statement helps to add new columns into
the existing table.

The syntax is:

ALTER TABLE<table_name>

ADD (column_specification);

Where table_name corresponds to the name of the table, column_specification


corresponds to the valid specification for a column (column_name and datatype)

Example:-

Page |7
Advanced Database Management System laboratory

1. To add ADDRESS column into the EMPLOYEE table with column width 30
and datatype CHARACTER is shown below:

ALTER TABLE EMPLOYEE

ADD (ADDRESS CHARACTER(30));

2. Instead of adding columns one by one we can add multiple columns in a table.
To add FATHER’S NAME and POST columns into EMPLOYEE table, the s
3. Statement is:

ALTER TABLE EMPLOYEE

ADD (FATHERS_NAME CHARACTER(30), POST CHARACTER(10));

Page |8
Advanced Database Management System laboratory

MODIFYING COLUMN IN EXISTING TABLE:-

The ALTER TABLE statement also offers the ability to modify columns in the existing
table without impacting any other data in the table. Using ALTER TABLE statement, we
can increase or decrease the column widths, changing a column from mandatory to
optional (NOT NULL to NULL) and vice versa.

The syntax is:

ALTERTABLE<table_name>

MODIFY(column_specification);

Where table_name corresponds to the name of the table, column_specification


corresponds to the valid specification for a column (column_name and datatype)

Example:-

To increase the length of CHARACTER type variable in NAME column in the


EMPLOYEE table from 30 to 35, use the following ALTER TABLE statement.

ALTER TABLE EMPLOYEE

MODIFY(NAME CHARACTER(35));

Page |9
Advanced Database Management System laboratory

DROPPING COLUMN:-

You cannot only modify columns that exist in your tables but you can also drop them
entirely if it is no longer required.

The syntax for dropping a column is:

ALTER TABLE<table_name>DROPCOLUMN<Column_name>;

This syntax is valid if you want to drop one column at a time.

EXAMPLE:

To drop the PHONE column from the EMPLOYEE table, the ALTER TABLE
statement is
ALTER TABLE EMPLOYEE

DROP COLUMN PHONE;

If user wishes to drop multiple columns, using the ALTER TABLE statement then to
follow the following syntax:

ALTER TABLE<table_name>

DROP(<column_name1>,<column_name2>);

P a g e | 10
Advanced Database Management System laboratory

EXAMPLE:

To drop the ADDRESS and POST column from the EMPLOYEE table, the ALTER
TABLE statement is:

ALTER TABLE EMPLOYEE

DROP(POST,ADDRESS);

P a g e | 11
Advanced Database Management System laboratory

Program-3 Implementation of Constraint

• Check Constraint

• Entity Integrity Constraint

• Referential Integrity Constraint

• Unique Constraint

• Null Value Constraint

Check Key Constraint:-


Syntax:
CREATE TABLE Table_name (
Column_name datatype,
CHECK (Condition)
);

Check Key Constraint:-


Syntax:
CREATE INDEX index_name
ON table_name (column1, column2);

P a g e | 12
Advanced Database Management System laboratory

Not Null Constraint :-


Syntax:
CREATE TABLE Table_name (
Column_name datatype NOT NULL,
);

P a g e | 13
Advanced Database Management System laboratory

Unique Key Constraint :-


Syntax:
CREATE TABLE Table_name (
Column_name datatype UNIQUE,
);

To Drop Unique Key Constraint :-


Syntax:
ALTER TABLE Table_name DROP UNIQUE (id);

P a g e | 14
Advanced Database Management System laboratory

Primary Key Constraint :-


Syntax:
CREATE Table Table_name (
Column_name datatype PRIMARY KEY
);

To Drop Primary Key Constraint :-


Syntax:
Alter table table_name
Drop primary key;

P a g e | 15
Advanced Database Management System laboratory

Default Constraint :-
Syntax:
Create table table_name (
Column_name datatype Default ‘value’ );

F
o
r
e
i
g
n

Key Constraint:-
Syntax:
CREATE TABLE Table_name (

PRIMARY KEY (Column_name),

FOREIGN KEY (column_name) REFERENCES table_name(column_name)

);

P a g e | 16
Advanced Database Management System laboratory

EXP
ERI
MENT -4

IMPLEMENTATIONN OF DML AND DCL COMMANDS

DML :-

DML stands for Data Manipulation Language. Tables and formulas are helpful when
communicating with data stored up to a point in a database through SQL, but a time comes
when we actually want to execute some fairly complicated data interactions. We will also need
the Data Manipulation Language in that situation. DML is a way to inform a database precisely
what we want it to do by conversing in a manner that it has been built to comprehend from the
scratch. When it comes to interacting within existing data, whether adding, moving, or deleting
data, it provides a convenient way to do so.

Command Description

Insert to insert a new row

Update to update existing row

Delete to delete a row

Merge merging two rows or two tables

Insert Values into Table:-

For inserting data into the tables, SQL has the INSERT command. The SQL INSERT
INTO Statement is used to add new rows of data to a table in the database.

Syntax

There are two basic syntaxes of the INSERT INTO statement which are shown
below.

P a g e | 17
Advanced Database Management System laboratory

Example:-

Let us insert values in the above table that we have created named EMPLOYEE and
having five columns namely E_CODE,NAME,SEX, PHONE,SALARY.

*The table Employee has following DATATYPES:

insert values in the table:

INSERT INTO EMPLOYEE(E_CODE,NAME,SEX,PHONE,SALARY)

VALUES ('TCSH','HARDIK','M',9996612662,20000.50)

P a g e | 18
Advanced Database Management System laboratory

UPDATE COMMAND

The UPDATE statement is used to modify the existing records in a table

UPDATE Syntax
UPDATE table name
SET column1 = value1, column2 = value2, ...
WHERE condition;

DELETE STATEMENT

The Delete Statement is used to delete any existing record in the table.
SYNTAX:

DELETE FROM table name WHERE condition;

P a g e | 19
Advanced Database Management System laboratory

The Table in SQL can be Retrieved using SELECT command.

DCL-

DCL stands for data control language. Data control language provides command to grant and
take back authority. DCL includes commands such as GRANT and REVOKE which mainly
deals with the rights, permissions and other controls of the database system

Command Description

Grant grant permission of right

Revoke take back permission.

• Grant:
SQL Grant command is specifically used to provide privileges to database objects for an
user. This command also allows users to grant permissions for other users too.
Syntax:
grant privilege name on object name to {username | public | role name}

Here privilege name is which permission has to be granted, object name is the name of the
database object, username is the user to which access should be provided, public is used to
permit the access to all the users.

• Revoke:
Revoke command withdraw user privileges on database objects if any granted. It does
operations opposite to the Grant command. When a privilege is revoked from a particular
user U, then the privileges granted to all other users by user U will be revoked.

Syntax:
revoke privilege name on object_name
from {user_name | public | role_name}

Example:
grant insert,
select on accounts to Ram

P a g e | 20
Advanced Database Management System laboratory

By the above command user ram has granted permissions on accounts database object like
he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts database
object has been removed.

P a g e | 21
Advanced Database Management System laboratory

Experiment 5:-Implementation of Data and Built in Functions in SQL.

ADD():-Returns addition of two numbers.

Sub():-Returns subtraction of two numbers.

Multiply:-Returns multiplication of given numbers.

P a g e | 22
Advanced Database Management System laboratory

Divide():-Returns the Quotient value of given numbers

Numeric Function:-
Abs():-Return to absolute value.

Power():-Return a number raised to an arbitrary power.

P a g e | 23
Advanced Database Management System laboratory

Round():-Round a number.

Sqrt():-Return the square root of a number.

Exp():-Return the base of natural logarithm raised to a power.

P a g e | 24
Advanced Database Management System laboratory

Greatest():-Returns the greatest number from given numbers.

Least():-Return the smallest number from numbers.

Mod():-Return module(remainder) of a division operator.

P a g e | 25
Advanced Database Management System laboratory

Trunc():-Truncates a number.

Floor():-Return the next smaller integer.

Ceil():-Return a next higher integer.

P a g e | 26
Advanced Database Management System laboratory

Program 6 :- Implementation of Nested Queries and Join Queries


Nested query is a query within another SQL query and embedded within the WHERE clause.

It is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.

Nested queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

There are a few rules that nested queries must follow –

➢ Nested queries must be enclosed within parentheses.


➢ A Nested query can have only one column in the SELECT clause, unless multiple
columns are in the main query for the Nested query to compare its selected columns.
➢ An ORDER BY command cannot be used in a sub query, although the main query
can use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a sub query.
➢ Nested queries that return more than one row can only be used with multiple value
operators such as the IN operator.
➢ The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
➢ A Nested query cannot be immediately enclosed in a set function.
➢ The BETWEEN operator cannot be used with a Nested query. However, the
BETWEEN operator can be used within the Nested query.
➢ Nested queries with the SELECT Statement
➢ Nested queries are most frequently used with the SELECT statement. The basic
syntax is as follows –

SELECT column_name [, column_name ] FROM table1 [, table2 ]

WHERE column_name OPERATOR

(SELECT column_name [, column_name ]

FROM table1 [, table2 ]

[WHERE])

FROM table1 [, table2 ] P a g e | 27


[WHERE])
Advanced Database Management System laboratory

SELECT column_name [, column_name ]

Example

Consider the CUSTOMERS table having the following records –

Now, let us check the following subquery with a SELECT statement.

SQL> SELECT *

FROM CUSTOMERS

WHERE ID IN (SELECT ID

FROM CUSTOMERS

WHERE SALARY > 4500) ;

This would produce the following result.

P a g e | 28
Advanced Database Management System laboratory

Nested queries with the INSERT Statement

Nested queries also can be used with INSERT statements. The INSERT statement uses the
data returned from the Nested queries to insert into another table. The selected data in the
Nested query can be modified with any of the character, date or number functions.

The basic syntax is as follows.

INSERT INTO table_name [ (column1 [, column2 ]) ]

SELECT [ *|column1 [, column2 ]

FROM table1 [, table2 ]

[ WHERE VALUE OPERATOR ]

Example

Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to


copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.

Nested queries with the UPDATE Statement

SQL> INSERT INTO CUSTOMERS_BKP

SELECT * FROM CUSTOMERS

WHERE ID IN (SELECT ID

FROM CUSTOMERS) ;

The Nested query can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a Nested query with the UPDATE
statement.

The basic syntax is as follows.

UPDATE table SET column_name = new_value

[ WHERE OPERATOR [ VALUE ]

(SELECT COLUMN_NAME

FROM TABLE_NAME) [ WHERE) ]

P a g e | 29
Advanced Database Management System laboratory

Example

Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS


table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.

SQL> UPDATE CUSTOMERS

SET SALARY = SALARY * 0.25

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

WHERE AGE >= 27 );

This would impact two rows and finally CUSTOMERS table would have the following
records.

Nested queries with the DELETE Statement

The Nested query can be used in conjunction with the DELETE statement like with any other
statements mentioned above.

The basic syntax is as follows.

DELETE FROM TABLE_NAME

[ WHERE OPERATOR [ VALUE ]

(SELECT COLUMN_NAME

FROM TABLE_NAME)

[ WHERE) ]

P a g e | 30
Advanced Database Management System laboratory

Example

Assuming, we have a CUSTOMERS_BKP table available which is a backup of the


CUSTOMERS table. The following example deletes the records from the CUSTOMERS
table for all the customers whose AGE is greater than or equal to 27.

SQL> DELETE FROM CUSTOMERS

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

WHERE AGE >= 27 );.

This would impact two rows and finally the CUSTOMERS table would have the following
records:

JOIN Queries :-
A JOIN query is used to combine rows from two or more tables, based on a related column
between them.

Let’s look at a selection from the “Orders” table:

P a g e | 31
Advanced Database Management System laboratory

Notice that the “CustomerID” column in the “Orders” table refers to the “CustomerID” in the
“Customers” table. The relationship between the two tables above is the “CustomerID”
column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that
selects records that have matching values in both tables:

Example

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders

INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

And it will produce something like this:

Different Types of SQL JOINS

Here are the different types of the JOINs in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables

P a g e | 32
Advanced Database Management System laboratory

• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table
• SQL INNER JOIN SQL LEFT JOIN SQL RIGHT JOIN SQL FULL OUTER
JOIN

P a g e | 33
Advanced Database Management System laboratory

Experiment 7 :- Implementation Of Cursors

A Cursor is a pointer to this context area. Oracle creates context area for processing an SQL
statement which contains all information about the statement.

The cursor is of two types.

• Implicit Cursor
• Explicit Cursor

Implicit Cursor

Whenever any DML operations occur in the database, an implicit cursor is created that holds
the rows affected, in that particular operation. These cursors cannot be named and, hence they
cannot be controlled or referred from another place of the code. We can refer only to the most
recent cursor through the cursor attributes.

Explicit Cursor

Programmers are allowed to create named context area to execute their DML operations to
get more control over it. The explicit cursor should be defined in the declaration section of
the PL/SQL block, and it is created for the 'SELECT' statement that needs to be used in the
code.

Below are steps that involved in working with explicit cursors.

• Declaring the cursor

Declaring the cursor simply means to create one named context area for the 'SELECT'
statement that is defined in the declaration part. The name of this context area is same
as the cursor name.

• Opening Cursor

Opening the cursor will instruct the PL/SQL to allocate the memory for this cursor. It
will make the cursor ready to fetch the records.

• Fetching Data from the Cursor

P a g e | 34
Advanced Database Management System laboratory

In this process, the 'SELECT' statement is executed and the rows fetched is stored in
the allocated memory. These are now called as active sets. Fetching data from the
cursor is a record-level activity that means we can access the data in a record-by-
record way.

Each fetch statement will fetch one active set and holds the information of that
particular record. This statement is same as 'SELECT' statement that fetches the
record and assigns to the variable in the 'INTO' clause, but it will not throw any
exceptions.

• Closing the Cursor

Once all the record is fetched now, we need to close the cursor so that the memory
allocated to this context area will be released.

Syntax:

DECLARE
CURSOR <cursor_name> IS <SELECT statement^>
<cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;

• In the above syntax, the declaration part contains the declaration of the cursor and the
cursor variable in which the fetched data will be assigned.
• The cursor is created for the 'SELECT' statement that is given in the cursor
declaration.
• In execution part, the declared cursor is opened, fetched and closed.

P a g e | 35
Advanced Database Management System laboratory

Cursor Attributes

Both Implicit cursor and the explicit cursor has certain attributes that can be accessed. These
attributes give more information about the cursor operations. Below are the different cursor
attributes and their usage.

Cursor Description
Attribute

%FOUND It returns the Boolean result 'TRUE' if the most recent fetch operation
fetched a record successfully, else it will return FALSE.

%NOTFOUND This works oppositely to %FOUND it will return 'TRUE' if the most
recent fetch operation could not able to fetch any record.

%ISOPEN It returns Boolean result 'TRUE' if the given cursor is already opened,
else it returns 'FALSE'

%ROWCOUNT It returns the numerical value. It gives the actual count of records that got
affected by the DML activity.

Example 1: In this example, we are going to see how to declare, open, fetch and close the
explicit cursor.

We will project the entire employee's name from emp table using a cursor. We will also use
cursor attribute to set the loop to fetch all the record from the cursor.

P a g e | 36
Advanced Database Management System laboratory

DECLARE
CURSOR guru99_det IS SELECT emp_name FROM emp;
lv_emp_name emp.emp_name%type;

BEGIN
OPEN guru99_det;

LOOP
FETCH guru99_det INTO lv_emp_name;
IF guru99_det%NOTFOUND
THEN
EXIT;
END IF;
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);
END LOOP;
Dbms_output.put_line(‘Total rows fetched is‘||guru99_det%R0WCOUNT);
CLOSE guru99_det;
END:
/

P a g e | 37
Advanced Database Management System laboratory

Output

Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY
Total rows fetched is 3

FOR Loop Cursor statement

"FOR LOOP" statement can be used for working with cursors. We can give the cursor name
instead of range limit in the FOR loop statement so that the loop will work from the first
record of the cursor to the last record of the cursor. The cursor variable, opening of cursor,
fetching and closing of the cursor will be done implicitly by the FOR loop.

Syntax:

DECLARE
CURSOR <cursor_name> IS <SELECT statement>;
BEGIN
FOR I IN <cursor_name>
LOOP
.
.
END LOOP;
END;

• In the above syntax, the declaration part contains the declaration of the cursor.
• The cursor is created for the 'SELECT' statement that is given in the cursor
declaration.
• In execution part, the declared cursor is setup in the FOR loop and the loop variable 'I'
will behave as cursor variable in this case.

Example 1: In this example, we will project the entire employee name from emp table using
a cursor-FOR loop.

P a g e | 38
Advanced Database Management System laboratory

DECLARE
CURSOR guru99_det IS SELECT emp_name FROM emp;
BEGIN
FOR lv_emp_name IN guru99_det
LOOP
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name.emp_name);
END LOOP;
END;
/

Output

Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY

P a g e | 39
Advanced Database Management System laboratory

Experiment no -8:- Implementation of Procedures and Functions

A Procedure in PL/SQL is a subprogram unit that consists of a group of PL/SQL statements


that can be called by name. Each procedure in PL/SQL has its own unique name by which it
can be referred to and called. This subprogram unit in the Oracle database is stored as a
database object.

Note: Subprogram is nothing but a procedure, and it needs to be created manually as per the
requirement. Once created they will be stored as database objects.

Below are the characteristics of Procedure subprogram unit in PL/SQL:

• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these PLSQL procedures can be made by referring to their name, to execute
the PL/SQL statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part
(optional).
• The values can be passed into Oracle procedure or fetched from the procedure
through parameters.
• These parameters should be included in the calling statement.
• A Procedure in SQL can have a RETURN statement to return the control to the
calling block, but it cannot return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called
from another block or through EXEC keyword.

Syntax:

CREATE OR REPLACE PROCEDURE


<procedure_name>
(
<parameterl IN/OUT <datatype>
..
.

P a g e | 40
Advanced Database Management System laboratory

)
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;

• CREATE PROCEDURE instructs the compiler to create new procedure in Oracle.


Keyword 'OR REPLACE' instructs the compile to replace the existing procedure (if
any) with the current one.
• Procedure name should be unique.
• Keyword 'IS' will be used, when the stored procedure in Oracle is nested into some
other blocks. If the procedure is standalone then 'AS' will be used. Other than this
coding standard, both have the same meaning.

Example1: Creating Procedure and calling it using EXEC

In this example, we are going to create an Oracle procedure that takes the name as input and
prints the welcome message as output. We are going to use EXEC command to call
procedure.

CREATE OR REPLACE PROCEDURE welcome_msg (p_name IN VARCHAR2)


IS
BEGIN
dbms_output.put_line (‘Welcome '|| p_name);
END;
/
EXEC welcome_msg (‘Guru99’);

Code Explanation:

• Code line 1: Creating the procedure with name 'welcome_msg' and with one
parameter 'p_name' of 'IN' type.

P a g e | 41
Advanced Database Management System laboratory

• Code line 4: Printing the welcome message by concatenating the input name.
• Procedure is compiled successfully.
• Code line 7: Calling the procedure using EXEC command with the parameter
'Guru99'. Procedure is executed, and the message is printed out as "Welcome
Guru99".

What is Function?

Functions are a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a
unique name by which it can be referred. These are stored as PL/SQL database objects.
Below are some of the characteristics of functions.

• Functions are a standalone block that is mainly used for calculation purpose.
• Function use RETURN keyword to return the value, and the datatype of this is
defined at the time of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory
in functions.
• Function with no DML statements can be directly called in SELECT query whereas
the function with DML operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part
(optional).
• The values can be passed into the function or fetched from the procedure through the
parameters.
• These parameters should be included in the calling statement.
• A PLSQL function can also return the value through OUT parameters other than
using RETURN.
• Since it will always return the value, in calling statement it always accompanies with
assignment operator to populate the variables.

P a g e | 42
Advanced Database Management System laboratory

Syntax

CREATE OR REPLACE FUNCTION


<procedure_name>
(
<parameterl IN/OUT <datatype>
)
RETURN <datatype>
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;

• CREATE FUNCTION instructs the compiler to create a new function. Keyword 'OR
REPLACE' instructs the compiler to replace the existing function (if any) with the
current one.
• The Function name should be unique.
• RETURN datatype should be mentioned.

P a g e | 43
Advanced Database Management System laboratory

• Keyword 'IS' will be used, when the procedure is nested into some other blocks. If the
procedure is standalone then 'AS' will be used. Other than this coding standard, both
have the same meaning.

Example1: Creating Function and calling it using Anonymous Block

In this program, we are going to create a function that takes the name as input and returns the
welcome message as output. We are going to use anonymous block and select statement to
call the function.

CREATE OR REPLACE FUNCTION welcome_msgJune ( p_name IN VARCHAR2)


RETURN VAR.CHAR2
IS
BEGIN
RETURN (‘Welcome ‘|| p_name);
END;
/

P a g e | 44
Advanced Database Management System laboratory

DECLARE
lv_msg VARCHAR2(250);
BEGIN
lv_msg := welcome_msg_func (‘Guru99’);
dbms_output.put_line(lv_msg);
END;
SELECT welcome_msg_func(‘Guru99:) FROM DUAL;

Code Explanation:

• Code line 1: Creating the Oracle function with name 'welcome_msg_func' and with
one parameter 'p_name' of 'IN' type.
• Code line 2: declaring the return type as VARCHAR2
• Code line 5: Returning the concatenated value 'Welcome' and the parameter value.
• Code line 8: Anonymous block to call the above function.
• Code line 9: Declaring the variable with datatype same as the return datatype of the
function.
• Code line 11: Calling the function and populating the return value to the variable
'lv_msg'.
• Code line 12: Printing the variable value. The output you will get here is "Welcome
Guru99"
• Code line 14: Calling the same function through SELECT statement. The return value
is directed to the standard output directly.

Similarities between Procedure and Function

• Both can be called from other PL/SQL blocks.


• If the exception raised in the subprogram is not handled in the subprogram exception
handling section, then it will propagate to the calling block.
• Both can have as many parameters as required.
• Both are treated as database objects in PL/SQL.

P a g e | 45
Advanced Database Management System laboratory

Procedure Vs. Function: Key Differences

Procedure Function
• Used mainly to a execute certain
• Used mainly to perform some calculation
process

• A Function that contains no DML


• Cannot call in SELECT statement statements can be called in SELECT
statement

• Use OUT parameter to return the


• Use RETURN to return the value
value

• It is not mandatory to return the


• It is mandatory to return the value
value

• RETURN will simply exit the • RETURN will exit the control from
control from subprogram. subprogram and also returns the value

• Return datatype will not be specified • Return datatype is mandatory at the time of
at the time of creation creation

P a g e | 46
Advanced Database Management System laboratory

Program-9 Implementation of Triggers in SQL:


TRIGGER: A trigger is a special type of stored procedure that automatically runs when an
event occurs in the database server.

Triggers are, in fact, written to be executed in response to any of the following events −

• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)

• A database definition (DDL) statement (CREATE, ALTER, or DROP).

• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or


SHUTDOWN).

Triggers can be defined on the table, view, schema, or database with which the event is
associated.

Triggers may use to provide referential integrity, to enforce complex business rules, or to
audit changes to data. The code within a trigger body, is made up of PL/SQL blocks.

Features of database triggers:

• To derive column values automatically.


• To enforces complex integrity constraints.
• To enforce complex business’s rules.
• To customize complex security Authorization.
• To maintain replicate tables.
• To audit data modifications.

Difference between Triggers and Procedures:

Triggers Procedures

It do not accept parameters. They can accept parameters.

A triggers is automatically executed without A stored procedure on other had needs to be


any action required by a user. explicitly invoked.

P a g e | 47
Advanced Database Management System laboratory

Creating Triggers:

The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR]| UPDATE [OR]| DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing


trigger with the trigger_name.

• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.

• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.

• [OF col_name] − This specifies the column name that will be updated.

• [ON table_name] − This specifies the name of the table associated with the trigger.

• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.

• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.

P a g e | 48
Advanced Database Management System laboratory

• WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.

Example: To start with, we will be using the CUSTOMERS table we had created and used in
the previous chapters −

Select * from customers;


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID >0)
DECLARE
sal_diff number;
BEGIN
sal_diff :=:NEW.salary -:OLD.salary;
dbms_output.put_line('Old salary: '||:OLD.salary);
dbms_output.put_line('New salary: '||:NEW.salary);
dbms_output.put_line('Salary difference: '|| sal_diff);
END;
/

P a g e | 49
Advanced Database Management System laboratory

When the above code is executed at the SQL prompt, it produces the following result −

Trigger created.

The following points need to be considered here −

• OLD and NEW references are not available for table-level triggers, rather you can
use them for record-level triggers.

• If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.

• The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (7,'Kriti',22,'HP',7500.00);

When a record is created in the CUSTOMERS table, the above create


trigger, display_salary_changes will be fired and it will display the following result −

Old salary:
New salary: 7500
Salary difference:

Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −

UPDATE customers
SET salary = salary +500
WHERE id =2;

P a g e | 50
Advanced Database Management System laboratory

When a record is updated in the CUSTOMERS table, the above create


trigger, display_salary_changes will be fired and it will display the following result −

Old salary: 1500


New salary: 2000
Salary difference: 500

P a g e | 51
Advanced Database Management System laboratory

Experiment 10:- Implementation of Embedded SQL


SQL is a dual mode database language, which can be used two ways, It can be used
interactively to define database objects and query and update operations. It can also
embedded in a programming language, so is called as Embedded SQL. In embedded SQL
approach the SQL statements are embedded directly into the program's source code, along
with other programming language statements. Special delimiters specify the beginning and
end of the SQL statements in the program.

Embedded SQL statements are used to perform the data access and manipulation tasks. A
special SQL precompiler accepts the combined source code (Code containing the
programming language statements) and the embedded SQL statements. It compiles the
combined code and converts into the executable form. This compilation process is slightly
different from the compilation of a program, which does not have embedded SQL statements.
The programming language in which the SQL statements are included is called the Host
Language Some of common host languages are C, COBOL, Pascal and FORTRAN. The
program is written in host language but whenever data access is needed SQL statements are
embedded This embedded SOL code is submitted to SQL precompiler.

Variables of host language can be referenced in embedded SQL statements to allow

the values calculated by the program to be used by the SQL statements. The host language
variables (also known as host variables) are also used by the embedded SQL statements to
receive the results of the SQL queries that allow the programming language to process the
retrieved values.

FEATURES OF EMBEDDED SQL

There are following important features of Embedded SQL:

➢ SQL is case insensitive and usually it is written in the style of host language.
Embedded SQL are prefixed by EXEC SQL to distinguish it from host language,
➢ If it Embedded SQL statement extends over multiple lines then same strategy is used
for continuation as used by the host language.
➢ Delimiter terminates every embedded SQL, In COBOL it is END EXEC and in C

it is a semicolon,

P a g e | 52
Advanced Database Management System laboratory

➢ SQL statements can refer host variables by prefixing colon with name of variable.
➢ Host variables should have data types appropriate to the purpose for which they are
used.
➢ Host variables and SQL columns can have the same name.

Structure of Embedded SQL

Structure of embedded SQL defines step by step process of establishing a connection with
DB and executing the code in the DB within the high level language.

Connection to DB

This is the first step while writing a query in high level languages. First connection to the DB
that we are accessing needs to be established. This can be done using the keyword
CONNECT. But it has to precede with ‘EXEC SQL’ to indicate that it is a SQL statement.

EXEC SQL CONNECT db_name;

EXEC SQL CONNECT HR_USER; //connects to DB HR_USER

Declaration Section

Once connection is established with DB, we can perform DB transactions. Since these DB
transactions are dependent on the values and variables of the host language. Depending on
their values, query will be written and executed. Similarly, results of DB query will be
returned to the host language which will be captured by the variables of host language. Hence
we need to declare the variables to pass the value to the query and get the values from query.
There are two types of variables used in the host language.

Host variable: These are the variables of host language used to pass the value to the query as
well as to capture the values returned by the query. Since SQL is dependent on host language
we have to use variables of host language and such variables are known as host variable. But
these host variables should be declared within the SQL area or within SQL code. That means
compiler should be able to differentiate it from normal C variables. Hence we have to declare
host variables within BEGIN DECLARE and END DECLARE section. Again, these declare
block should be enclosed within EXEC SQL and ‘;’.

Indicator Variable: These variables are also host variables but are of 2 byte short type
always. These variables are used to capture the NULL values that a query returns or to
INSERT/ UPDATE any NULL values to the tables. When it is used in a SELECT query, it
captures any NULL value returned for any column. When used along with INSERT or

P a g e | 53
Advanced Database Management System laboratory

UPDATE, it sets the column value as NULL, even though the host variable has value. If we
have to capture the NULL values for each host variable in the code, then we have to declare
indicator variables to each of the host variables. These indicator variables are placed
immediately after the host variable in a query or separated by INDICATOR between host and
indicator variable.

SIMPLE EMBEDDED SQL STATEMENTS

The simplest types of embedded SQL statements are those that do not produce any query
results. For example: Statements like INSERT, UPDATE, DELETE and CREATE TABLE
In order to embed SQL statements in host language SQL Communication Area and
WHENEVER statement plays a major role, whose description is as follows

SQL Communications Area

The DBMS uses an SQL Communications Area (SQLCA) to report runtime errors to the
application program. The SQLCA contains error variables and status indicators. An
application program can examine the SQLCA to determine the success or failure of each SQL
statement

To use the SQLCA, at the start of the program we include theline

EXEC SOL INCLUDE sqlca;

This tells the precompiler to include the SOLCA data structure in the program. SQLCA
contain a SQLCODE variable, which is used to check the errors after the execution of SQL
statements. Its value may be as follows:

Value Description
0 If statement executed successfully
-ve If an error occurred during the execution of SQL statement and the value in
SQLCODE indicates the specific error that has occurred.
+ve Positive value is returned if statement executed successfully and an exceptional
condition occurred, such as no more rows returned by a SELECT statement

For example: SQLCA.SQLCODE<0 check is used to detect for unsuccessful completion of


the latest executed SQL statement.

P a g e | 54
Advanced Database Management System laboratory

Whenever statement

Every embedded SQL statement can generate an error. Thus checking for success after every
SQL statement would be quite laborious, so the Oracle precompiler provides an alternative
method to simplify error handling. The WHENEVER statement is a directive to the
precompiler to automatically generate code to handle errors after every SQL statement.

The format of the WHENEVER statement is:

EXEC SQL WHNEVER <condition><action>

The WHENEVER statement consists of a condition and an action to be taken if the condition
occurs, such as continuing with the next statement calling a routine, go to a labelled
statement, or stopping.

The condition can be one of the following:

Condition Description
SQLERROR It tells the precompiler to generate code to handle errors
(SQLCODE <0).
SQLWARNING It tells the precompiler to generate code to handle warnings
(SQLCODE > 0).
NOT FOUND It tells the precompiler to generate code to handle the specific warning
that a retrieval operation has found no more records.

Action Description
CONTINUE To ignore the condition and proceed to the next statement
DO To transfer control to an error handling function
DO BREAK To place an actual break statement in the program

DO CONTINUE To place an actual continue statement in the program


GOTO label To transfer control to the specified label.
STOP To rollback all uncommitted work and terminate the program

P a g e | 55

You might also like