Advance Database Management System Laboratory (B)
Advance Database Management System Laboratory (B)
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.
Page |2
Advanced Database Management System laboratory
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
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:-
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<table_name>
(<column_specification>,<column_specification> …..);
• Column name
• Data type
• Length of column, if any
• Constraints, if applicable
Example:-
E_CODE CHAR(4),
NAME CHAR(30),
Page |6
Advanced Database Management System laboratory
SEX CHAR(1),
PHONE INT,
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:
ALTER COMMAND
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.
ALTER TABLE<table_name>
ADD (column_specification);
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:
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:
Page |8
Advanced Database Management System laboratory
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.
ALTERTABLE<table_name>
MODIFY(column_specification);
Example:-
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.
ALTER TABLE<table_name>DROPCOLUMN<Column_name>;
EXAMPLE:
To drop the PHONE column from the EMPLOYEE table, the ALTER TABLE
statement is
ALTER TABLE EMPLOYEE
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:
DROP(POST,ADDRESS);
P a g e | 11
Advanced Database Management System laboratory
• Check Constraint
• Unique Constraint
P a g e | 12
Advanced Database Management System laboratory
P a g e | 13
Advanced Database Management System laboratory
P a g e | 14
Advanced Database Management System laboratory
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 (
);
P a g e | 16
Advanced Database Management System laboratory
EXP
ERI
MENT -4
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
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.
VALUES ('TCSH','HARDIK','M',9996612662,20000.50)
P a g e | 18
Advanced Database Management System laboratory
UPDATE COMMAND
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:
P a g e | 19
Advanced Database Management System laboratory
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:
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
P a g e | 22
Advanced Database Management System laboratory
Numeric Function:-
Abs():-Return to absolute value.
P a g e | 23
Advanced Database Management System laboratory
Round():-Round a number.
P a g e | 24
Advanced Database Management System laboratory
P a g e | 25
Advanced Database Management System laboratory
Trunc():-Truncates a number.
P a g e | 26
Advanced Database Management System laboratory
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.
[WHERE])
Example
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
P a g e | 28
Advanced Database Management System laboratory
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.
Example
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.
(SELECT COLUMN_NAME
P a g e | 29
Advanced Database Management System laboratory
Example
This would impact two rows and finally CUSTOMERS table would have the following
records.
The Nested query can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
P a g e | 30
Advanced Database Management System laboratory
Example
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.
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
• (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
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.
• 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.
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.
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.
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" 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
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.
• 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:
P a g e | 40
Advanced Database Management System laboratory
)
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
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.
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 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.
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.
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.
P a g e | 45
Advanced Database Management System laboratory
Procedure Function
• Used mainly to a execute certain
• Used mainly to perform some calculation
process
• 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
Triggers are, in fact, written to be executed in response to any of the following events −
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.
Triggers Procedures
P a g e | 47
Advanced Database Management System laboratory
Creating Triggers:
Where,
• {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 −
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 −
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.
• 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 −
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
P a g e | 51
Advanced Database Management System laboratory
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.
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.
➢ 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 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.
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.
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
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
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
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 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.
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
P a g e | 55