0% found this document useful (0 votes)
2 views

DBMS_bcom_unit-5

PL/SQL is Oracle's procedural language that combines SQL with programming constructs like loops and conditionals, enhancing performance and programming ease. It consists of blocks with optional declaration, mandatory execution, and exception handling sections, and supports various data types and structures. Procedures and functions are key components, with procedures performing tasks without returning values and functions returning a single value, both benefiting from modularization and improved performance.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DBMS_bcom_unit-5

PL/SQL is Oracle's procedural language that combines SQL with programming constructs like loops and conditionals, enhancing performance and programming ease. It consists of blocks with optional declaration, mandatory execution, and exception handling sections, and supports various data types and structures. Procedures and functions are key components, with procedures performing tasks without returning values and functions returning a single value, both benefiting from modularization and improved performance.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT-V

Procedural SQL(PL/SQL)
PL/SQL is Oracle’s procedural language, it comprises the standard language
of SQL and a wide array of commands that enable us to control the execution of SQL
statements according to different conditions. Options such as loops and IF…THEN
statements give PL/SQL the power of third generation programming languages.
The advantages of using PL/SQL are several and generally associated with
performance and ease of programming.
 Reduction in the number of calls from an application to the server.
 Portability between the platforms where oracle is executed.
 Error management.
Basic structure of PL/SQL block

Declaration section:
This section is optional. However , the if block uses variable or constants, all
must be declared before being referenced in a command. To initiate this section the
keyword declare should be used .
 Declare an identifier name
 Declare the identifier type(constant or variable)
 Declare the identifier datatype
 Attribute a content to the identifier
Each variable or constant should be specifies with its name , type and an optional
initiate value. All the statements ended with a semicolon.
Execution section:
This section is initiated with the begin declaration . The commands specified
in this section should follow the same rules used for the execution of a command in

DBMS Page 1
SQL. It is mandatory that they end with a semicolon. This section may contain SQL
commands , logical control commands etc.
Exception section:
This section serves to handle an error which may occur during execution of a
PL/SQL program. When an error happens within a PL/SQL program, an error
message is displayed.
Declare
a number
b number
c number
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line(‘sum of two numbers is ‘||c);
end;

OUT PUT
Enter value for a 15
Enter value for b 20
Sum of two numbers is 35

PL/SQL Language Elements


Like other programming languages PL/SQL also have specific character sets,
operators, indicators,punctuations, identifiers, comments, etc.
Character Set
A PL/SQL program consists of text having specific set of characters. Character set
may include the following characters:
– Alphabets, both in upper case [A–Z] and lower case [a–z]
– Numeric digits [0–9]
– Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , __ # $ & |
{}?[]
– Blank spaces, tabs, and carriage returns.
Lexical Units

DBMS Page 2
A line of PL/SQL program contains groups of characters known as lexical units,
which can be classified as follows:
– Delimiters
– Identifiers
– Literals
– Comments
Delimiters
A delimiter is a simple or compound symbol that has a special meaning to PL/SQL.
Simple symbol consists of one character, while compound symbol consists of more
than one character.
PL/SQL supports following
simple symbol delimiters:
+ − * / => <; % _ , ( ) @ : __
Compound symbol delimiters legal in PL/SQL are as follows:
<>! =∼= ˆ= <=>= := ** .. || << >>
Identifiers
Identifiers are used in the PL/SQL programs to name the PL/SQL program items as
constants, variables, cursors, cursor variables, subprograms, etc. Identifiers can
consists of alphabets, numerals, dollar signs, underscores, and number signs only.
Any other characters like hyphens, slashes, blank spaces, etc. are illegal.
Literals
A literal is an explicitly defined character, string, numeric, or Boolean value, which is
not represented by an identifier. In the following sections we will discuss about each
of these literals in detail:
Numeric Literals
A numeric literal is an integer or a real value. An integer literal may be a positive,
negative, or unsigned whole number without a decimal point. Some examples of
integer numeric literals are as follows:
100 006 −10 0 +10
A real literal is a positive, negative, or unsigned whole

Character Literals

DBMS Page 3
A character literal is an individual character enclosed by single quotes
(apostrophes).Character literals include all the printable characters in the PL/SQL
character set: letters, numerals, spaces, and special symbols. Some examples
of character literals are as follows:
“A” “@” “5” “?” “,” “(”
String Literals
A character string can be represented by an identifier or explicitly written as a string
literal. A string literal is enclosed within single quotes and may consist of one or more
characters. Some examples of string literals are as follows:
“Good Morning!”
“TATA INFOTECH LTD”
“04-MAY-00”
Boolean Literals
Boolean literals are the predefined values TRUE, FALSE, and NULL.
Comments
Comments are used in the PL/SQL program to improve the readability and
understandability of a program. A comment can appear anywhere in the program
code. The compiler ignores comments. Generally, comments are used to describe the
purpose and use of each code segment. A PL/SQL comment may be a single-line or
multiline.
Single-Line Comments
Single-line comments begin with a double hyphen (–) anywhere on a line and extend
to the end of the line.

Steps to Create a PL/SQL Program


1. First a notepad file can be created as typing in the Oracle SQL editor. the command
to create a file,
2. Then a Notepad file will appear and at the same time background Oracle
will be disabled
3. We can write our PL/SQL program in that file, save that file, and we can execute
that program in the Oracle editor . In this program Cursor (Current Set of Records)
concept is used which we will see in the following pages. Here content of EMP table
is opened by the cursor and they are displayed by the DBMS OUTPUT package.
Command IF is used to check whether the cursor has been opened successfully by
using %Found attribute.

DBMS Page 4
4. Then we can execute that file as follows

Procedure
A procedure is a subprogram that performs some specific task, and stored in the data
dictionary. A procedure must have a name, so that it can be invoked or called by any
PL/SQL program that appears within an application.
Procedures can take parameters from the calling program and perform the specific
task. Before the procedure or function is stored, the Oracle engine parses and
compiles the procedure or function. When a procedure is created,
the Oracle automatically performs the following steps:
1. Compiles the procedure
2. Stores the procedure in the data dictionary
Benefits of Procedures and Functions
Stored procedures and functions have many benefits in addition to modularizing
application development.
1. It modifies one routine to affect multiple applications.
2. It modifies one routine to eliminate duplicate testing.
3. It ensures that related actions are performed together, or not at all, by doing the
activity through a single path.
4. It avoids PL/SQL parsing at runtime by parsing at compile time.
5. It reduces the number of calls to the database and database network traffic by
bundling the commands.
Defining and Creating Procedures
A procedure consists of two parts: specification and body. The specification
starts with keyword PROCEDURE and ends with parameter list or procedure name.
The procedures may accept parameters or may not. Procedures that do not accept
parameters are written parentheses. The procedure body starts with the keyword IS
and ends with keyword END. The procedure body is further subdivided into three
parts:
1. Declarative part which consists of local declarations placed between keywords IS
and BEGIN.
2. Executable part, which consists of actual logic of the procedure, included between
keywords BEGIN and EXCEPTION. At least one executable statement is a must in
the executable portion of a procedure. Even a
single NULL statement will do the job.

DBMS Page 5
3. Error/Exception handling part, an optional part placed between EXCEPTION and
END.
The syntax for creating a procedure is follows:
CREATE OR REPLACE PROCEDURE [schema.] package name
[(argument {IN, OUT, IN OUT} data type,. . . . . . . . .)] {IS, AS}
[local variable declarations]
BEGIN
executable statements
EXCEPTION
exception handlers
END [procedure name];
Create: Creates a new procedure, if a procedure of same name already exists, it gives
an error.
Replace: Creates a procedure, if a procedure of same name already exists, it replace
the older one by the new procedure definition.
Schema: If the schema is not specified then procedure is created in user’s current
schema.
Argument: It is the name of the argument to the procedure.
IN: Specifies that a value for the argument must be specified when calling the
procedure.
OUT: Specifies that the procedure pass a value for this argument back to its calling
environment after execution.
IN OUT: Specifies that a value for the argument must be specified when calling the
procedure and that the procedure passes a value for this argument back to its calling
environment after execution. If no value is specified then it takes the default value IN.
Datatype:
It is the unconstrained datatype of an argument. It supports any data type
supported by PL/SQL. No constraints like size constraints or NOT NULL constraints
can be imposed on the data type. However, you can
put on the size constraint indirectly.
Executing/Invoking a Procedure
The syntax used to execute a procedure depends on the environment from
which the procedure is being called. From within SQLPLUS, a procedure can be
executed by using the EXECUTE command, followed by the procedure name. Any

DBMS Page 6
arguments to be passed to the procedure must be enclosed in parentheses following
the procedure name.
Removing a Procedure
To remove a procedure completely from the database, following command is
used:
DROP PROCEDURE <PROCEDURE NAME

Function
A Function is similar to procedure except that it must return one and only one
value to the calling program. Besides this, a function can be used as part of SQL
expression, whereas the procedure cannot.
Difference Between Function and Procedure
Before we look at functions in deep, let us first discuss the major differences between
a function and a procedure.
1. A procedure never returns a value to the calling portion of code, whereas a function
returns exactly one value to the calling program.
2. As functions are capable of returning a value, they can be used as elements of SQL
expressions, whereas the procedures cannot. However, user-defined functions cannot
be used in CHECK or DEFAULT constraints and cannot manipulate database values,
to obey function purity rules.
3. It is mandatory for a function to have at least one RETURN statement, whereas for
procedures there is no restriction. A procedure may have a RETURN statement or
may not. In case of procedures with RETURN
statement, simply the control of execution is transferred back to the portion of code
that called the procedure.
CREATE OR REPLACE FUNCTION [schema.] functionname
[(argument IN datatype, . . . .)] RETURN datatype {IS,AS}
[local variable declarations];
BEGIN
executable statements;
EXCEPTION
exception handlers;
END [functionname];
where RETURN datatype is the datatype of the function’s return value. It can be any
PL/SQL datatype. Thus a function has two parts: function specification and function

DBMS Page 7
body. The function specification begins with keyword FUNCTION and ends with
RETURN clause which indicates the datatype of the value returned by the
function. Function body is enclosed between the keywords IS and END. Sometimes
END is followed by function name, but this is optional. Like procedure, a function
body also is composed of three parts: declarative part, executable part, and an optional
error/exception handling part.
Removing a Function
To remove a function, use following command:
DROP FUNCTION <FUNCTION NAME>;
Parameters
Parameters are the link between a subprogram code and the code calling the
subprogram. Lot depends on how the parameters are passed to a subprogram. Hence it
is absolutely necessary to know more about parameters, their modes,their default
values, and how subprograms can be called without passing all the parameters.
Parameter Modes
Parameter modes define the behavior of formal parameters of subprograms. There are
three types of parameter modes: IN, OUT, IN/OUT.
IN Mode
IN mode is used to pass values to the called subprogram. In short this is an input to
the called subprogram. Inside the called subprogram, an IN parameter acts like a
constant and hence it cannot be assigned a new value.
The IN parameter in actual parameter list can be a constant, literal, initialized
variable, or an expression. IN parameters can be initialized to default values, which is
not the case with IN/OUT or OUT parameters.
It is important to note that IN mode is the default mode of the formal parameters. If
we do not specify the mode of a formal parameter it will be treated as an IN mode
parameter.
OUT Mode
An OUT parameter returns a value back to the caller subprogram. Inside the
subprogram, the parameter specified with OUT mode acts just like any locally
declared variable. Its value can be changed or referenced in expressions, just like any
other local variables.
The points to be noted for an OUT parameter are:
1. The parameter (in actual argument list) corresponding to OUT parameter must be a
variable; it cannot be a constant or literal.

DBMS Page 8
2. Formal OUT parameters are by default initialized to NULL, so we cannot
constraint the formal OUT parameters by NOT NULL constraint.
3. The parameter (in actual argument list) corresponding to OUT parameter can have
a value before a call to subprogram, but the value is lost as soon as a call is made to
the subprogram.
IN/OUT
An IN/OUT parameter performs the duty of both IN parameter as well as OUT
parameter. It first passes input value (through actual argument) to the called
subprogram and then inside subprogram it receives a new value
which will be assigned finally to the actual parameter. In short, inside the called
subprogram, the IN/OUT parameter behaves just like an initialized local variable.
Like OUT parameter, the parameter in the actual argument list that corresponds to
IN/OUT parameter, must be a variable, it cannot be a constant or an expression. If the
subprogram exits successfully, PL/SQL assigns value to actual parameters, however,
if the subprogram exits with unhandled exception, PL/SQL does not assign values to
actual parameters.

Packages in SQL
A package can be defined as a collection of related program objects such as
procedures, functions, and associated cursors and variables together as a unit in the
database. In simpler term, a package is a group of related procedures
and functions stored together and sharing common variables, as well as local
procedures and functions. A package contains two separate parts: the package
specification and the package body.
Advantages of Packages
Packages offer a lot of advantages. They are as follows.
1. Stored packages allow us to sum up (group logically) related stored procedures,
variables, and data types, and so forth in a single-named, stored unit in the database.
This provides for better orderliness during the development process. In other words
packages and its modules are easily understood because of their logical grouping.
2. Grouping of related procedures, functions, etc. in a package also make privilege
management easier. Granting the privilege to use a package makes all components of
the package accessible to the grantee.

DBMS Page 9
3. Package helps in achieving data abstraction. Package body hides the details of the
package contents and the definition of private program objects so that only the
package contents are affected if the package body
changes.
4. An entire package is loaded into memory when a procedure within the package is
called for the first time. This load is completed in one operation, as opposed to the
separate loads required for standalone procedures.
Therefore, when calls to related packaged procedures occur, no disk I/O is necessary
to execute the compiled code already in memory. This results in faster and efficient
operation of programs.
5. Packages provide better performance than stored procedures and functions because
public package variables persist in memory for the duration of a session. So that they
can be accessed by all procedures and functions that
try to access them.
6. Packages allow overloading of its member modules. More than one function in a
package can be of same name. The functions are differentiated, depending upon the
type and number of parameters it takes.
Parts of Package
A Package has two parts. They are:
– Package specification
– Package body
Package Specification
The specification declares the types, variables, constants, exceptions, cursors, and
subprograms that are public and thus available for use outside the package. In case in
the package specification declaration there is only types, constants, exception, or
variables, then there is no need for the package body because package specification
are sufficient for them. Package body is required when there is subprograms like
cursors, functions, etc.
Package Body
The package body fully defines subprograms such as cursors, functions, and
procedures. All the private declarations of the package are included in the package
body. It implements the package specification. A package specification and the
package body are stored separately in the database. This allows calling objects to
depend on the specification only, not on both. This separation enables to change the
definition of program object in the package body without causing Oracle to interfere

DBMS Page 10
with other objects that call or reference the program object. Oracle invalidates the
calling object if the package specification is changed.
Creating a Package
A package consists of package specification and package body. Hence creation of a
package involves creation of the package specification and then creation of the
package body. The package specification is declared using the CREATE PACKAGE
command
The syntax for package specification declaration is as follows.
CREATE[OR REPLACE] PACKAGE <package name>
[AS/IS]
PL/SQL package specification
All the procedures, sub programs, cursors declared in the CREATE PACKAGE
command are described and implemented fully in the package body along with private
members. The syntax for declaring a package body is as
follows:
CREATE[OR REPLACE] PACKAGE BODY <package name>
[AS/IS]
PL/SQL package body
Removing a Package
A package can be dropped from the database just like any other table or database
object. The exact syntax of the command to be used for dropping a package is:
DROP PACKAGE <PACKAGE NAME>;

Exceptions Handling

During execution of a PL/SQL block of code, Oracle executes every SQL sentence
within the PL/SQL block. If an error occurs or an SQL sentence fails, Oracle
considers this as an Exception. Oracle engine immediately tries
to handle the exception and resolve it, by raising a built-in Exception handler.
Introduction to Exceptions
One can define an EXCEPTION as any error or warning condition that arises during
runtime. The main intention of building EXCEPTION technique is to continue the
processing of a program even when it encounters runtime error or warning and

DBMS Page 11
display suitable messages on console so that user can handle those conditions next
time.
EXCEPTION
WHEN exception name THEN
User defined action to be carried out.
Advantages of Using Exceptions
1. Control over abnormal exits of executing programs on encountering error
conditions, hence the behavior of application becomes more reliable.
2. Meaningful messages can be flagged so that the developer can become aware of
error and warning conditions and act upon them.
3. In traditional error checking system, if same error is to be checked at several places,
you are required to code the same error check at all those places. But with exception
handling technique, we will write the exception for that particular error only once in
the entire code. Whenever that type error occurs at any place in code, the exceptional
handler will automatically raise the defined exception.
4. Being a part of PL/SQL, exceptions can be coded at suitable places and can be
coded isolated like procedures and functions. This improves the overall readability of
a PL/SQL program.
5. Oracle’s internal exception mechanism combined with user-defined exceptions,
considerably reduce the development efforts required for cumbersome error handling.

Triggers
A trigger is procedural SQL code that is automatically invoked by the
RDBMS upon the occurrence of a given data manipulation event. Some of the points
about trigger as follows.
 A trigger is invoked before or after a data row is inserted, updated, or deleted.
 A trigger is associated with a database table.
 Each database table may have one or more triggers.
 A trigger is executed as part of the transaction that triggered it.
 Triggers can be used to update table values, insert records in tables, and call
other stored procedures.

There are two types of triggers which can be used in tables


Statement level triggers

DBMS Page 12
This type of trigger is executed once, before or after the triggering statement is
completed.
Row level triggers
This trigger requires use of the FOR EACH ROW keywords .This type of
trigger is executed once for each row affected by the triggering statement.
A trigger may be fired before or after one of the activation commands(INSERT,
UPDATE, DELETE) is executed. A table can contain up to 12 triggers associated
with the activation commands and the firing moment. There are six row level type and
six statement level triggers.
 BEFORE INSERT
 AFTER INSERT
 BEFORE UPDATE
 AFTER UPDATE
 BEFORE DELETE
 AFTER DELETE
Syntax:
Create [or replace]trigger trigger_name
{before|after}
{INSERT|UPDATE|DELETE[OF column[,column]…]}
On table
[[REFERENCING{OLD[AS]old[NEW[AS]new]|
NEW[AS]new[OLD[AS]old]}]
FOR EACH ROW
[WHEN (condition)]]
PL/SQL statements
Ex:
Create or replace trigger stu_trigger after insert or update of m1,m2,m3 on
student
Begin
Update student set tot=m1+m2+m3 where sno=:OLD.SNO;
End;
Removing Trigger

When you delete a table , all trigger objects are deleted with it. To
delete a trigger the following command is used

DBMS Page 13
Drop trigger trigger_name;

Write about SQL joins


SQL joins are used to relate information in different tables. A join condition is
a part of the SQL query that retrieves rows from two or more tables. A SQL join
condition is used in the SQL where clause of select, update, delete statement.
Syntax:
Select col1,col2,col3… from talble1,table2
Where table1.col=table2.col;
SQL joins can be classified into EQUI join and non Equi join.
SQL Equi joins:
It is a simple sql join condition which uses the equal sign as the comparison
operator. Two types of equi joins are SQL outer join and SQL inner join.
SQL non equi joins
It is a sql join condition which makes use of some comparison operator
other than the equal sign like >, <, >=,<=
SQL equi joins
An equi join is further classified into two categories
 SQL Inner join
 SQL Outer join
SQL inner join
All the rows returned by the SQL query satisfy the sql join condition specified.
Ex: If you want to display the product information for each order the query will be as
given below. Since you are retrieving the data from two tables , you need to identify
the common column between these two tables , which is the product_id.

Select order_id,product_name,unit_price,supplier_name,total_units from


product,order_items
Where order_items.product_id=product.product_id;
The column must be referenced by the table name in the join condition, because
product_id is a column in both the tables and needs a way to be identified . this avoids
ambiguity in using the columns in the SQL select statement.
SQL outer join

DBMS Page 14
This sql join condition returns all rows from both tables which satisfy the join
condition along with rows which do not satisfy the join condition from one of the
tables. The sql outer join operator in oracle is + and is used one side of the join
condition only.
The syntax differs for different RDBMS implementation. Few of them
represent the join conditions sa “sql left outer join”, “sql right outer join”.
If you want to display all the product data along with order items data, with
null values displayed for order items if a product has no order item, the sql query for
outer join would be as shown below.
Select p.product_id, p.product_name, o.order_id, o.total_units from
order_items o, product p
Where o.product_id(+)=p.product_id;
If the + operator is used in the left side of the join condition it is equivalent to left
outer join . if used on the right side of the join condition it is equivalent to right outer
join.
SQL self join
A self join is a type of sql join which is used to join a table to itself,
particularly when the table has a “foreign key” that references it own “primary key” .
it is necessary to ensure that the join statement defines an alias for both copies of the
table to avoid column ambiguity.
Ex:
Select a.sales_person_id,a.name,a.manager_id,b.sales_person_id,b.name from
sales_person a, sales_person b where a.manager_id=b.sales_person_id;

SQL non equi join


A non equi join is a sql join whose condition is established using all
comparison operators except the equal(=) operator. Like >=,<=,<,>
Ex
If you want to find the names of students who are not studying either
economics , the sql query would be like,
Select first_name, last_name,subject from student
Where subject!=’economics’;

DBMS Page 15
SQL indexes
Index in SQL is created on existing tables to retrieve the rows quickly. When
there are thousands of records in a table , retrieving information will take a long time.
Therefore indexes are created on columns which are accessed frequently , so that the
information can be retrieved quickly.
An index can be created on a single column or set of columns in a database
table. A table index is a database structure that arranges the values of one or more
columns in a database table in specific order. The table index has pointers to the
values stored in specified column or combination of columns of a table. These
pointers are ordered depending on the sort order specified in the index.
When index is created , it first sorts the data and then it assigns a RowId for each row.
Explicit indexes are created by the user.
Syntax: create index <index_name>on tablename(col1,col2…);
 Index_name is the name of the index
 Tablename is the name of the table to whichthe indexed column belongs.
 Col1,col2 is the list of columns which make up the index.
Ex: create index stu_index on student(sno);
Syntax to unique index
create unique index<index_name>on<table_name>(col1,col2…)
Creating a unique index guarantees that any attempt to duplicate key values fails. Data
validation occurs in the same manner , and the query optimizer does not differentiate
between a unique index created by a constraint or manually created. However , you
should create a unique constraint on the column when data integrity is the objective.
Ex:create unique index s_index on student(sno);
In oracle there are two types of SQL index namely , implicit and explicit.
Implicit indexes:
These indexes are created when a column is explicit defined with primary key,
unique key constraint.
Drop index
By using this command index can be dropped.
Syntax : drop index <index_name>
Ex: drop index s_index;
DCL Commands with example:

DBMS Page 16
DCL commands are used to enforce database security in a multiple user
database environment. Two types of DCL commands are GRANT and REVOKE.
Only Database Administrator's or owners of the database object can provide/remove
privileges on a database object.
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the database
objects to the users.
The Syntax for the GRANT command is:
SQL>GRANT privilege_name/all
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];

privilege_name is the access right or privilege granted to the user. Some of the access
rights are ALL, EXECUTE, and SELECT.

Object_name is the name of an database object like TABLE, VIEW, STORED PROC
and SEQUENCE.

User_name is the name of the user to whom an access right is being granted.

User_name is the name of the user to whom an access right is being granted.

PUBLIC is used to grant access rights to all users.

ROLES are a set of privileges grouped together.

WITH GRANT OPTION - allows a user to grant access rights to other users.

For Example: GRANT SELECT ON employee TO user1;This command grants a


SELECT permission on employee table to user1.You should use the WITH GRANT
option carefully because for example if you GRANT SELECT privilege on employee
table to user1 using the WITH GRANT option, then user1 can GRANT SELECT
privilege on employee table to another user, such as user2 etc. Later, if you REVOKE
the SELECT privilege on employee from user1, still user2 will have SELECT
privilege on employee table.
Ex: SQL> Grant all privileges on employee to user1;

DBMS Page 17
SQL REVOKE Command:
The REVOKE command removes user access rights or privileges to the database
objects.
The Syntax for the REVOKE command is:
SQL>REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
For Example: REVOKE SELECT ON employee FROM user1;This command will
REVOKE a SELECT privilege on employee table from user1.When you REVOKE
SELECT privilege on a table from a user, the user will not be able to SELECT data
from that table anymore. However, if the user has received SELECT privileges on
that table from more than one user, he/she can SELECT from that table until everyone
who granted the permission revokes it. You cannot REVOKE privileges if they were
not initially granted by you.
Ex: SQL> Revoke all privileges on employee from user1;
UPDATABLE VIEWS:
The SQL UPDATE VIEW command can be used to modify the data of a view.
All views are not updatable. So, UPDATE command is not applicable to all
views. An updatable view is one which allows performing an UPDATE command on
itself without affecting any other table
To create an updatable view:-
1. The view is defined based on only one table.
2. The view must include the PRIMARY KEY column and NOT NULL columns of
the table
based upon which the view has been created.
3. The view should not have any field made out of aggregate functions.
4. The view must not have any DISTINCT clause in it's definition.
5. The view must not have any GROUP BY or HAVING clause in it's definition.
6. The view must not have any SUBQUERIES in it's definitions.
7. If the view you want to update is based upon another view, the later should be
updatable.
8. Any of the selected output fields (of the view) must not use constants, strings or
value expressions.
Syntax

DBMS Page 18
SQL>UPDATE < view_name >
SET<column1>=<value1>,<column2>=<value2>,.....
WHERE <condition>;
Parameters
Name Description
view_name Name of the virtual table or view where data will be
modified.
column1,column Name of the columns of the table.
2
value1,value2 Values for the columns which is going to be updated.
condition Condition or criteria.
Example:
Sample view: Studentview
To update the view 'Studentview' with following conditions -
1. 'Ph_No' must be set at 9998887771,
2. 'Course' must be 'BSc',
The following SQL statement can be used :
SQL>UPDATE studentview
SET Ph_No=9876543210
WHERE Course=’BSc’;
Output:
1 row(s) updated.

Sequences
SQL provides an automatic sequence generated of numeric values, which can a
maximum values upto 38 digits. A sequence can be define to
Generate number in ascending or descending order
Provide intervals between numbers
Sequence can be created by issuing the following statement that references the
sequence. Sequences are creating independent of the tables that it may be used.
The general syntax for creating a sequence is:
CREATE SEQUENCE sequence name
START WITH VALUE
INCREMENT BY VALUE
MINVALUE VALUE

DBMS Page 19
MAXVALUE VALUE/NOMAXVALUE
CYCLE/NOCYCLE;
In the above syntax:
Sequence name: It specifies the name of the sequence which can be used while
creating a table.
Increment by: It specifies the interval between sequence numbers. It can be any
positive or negative value, but not zero. If this clause is omitted, the default value is
one.
MinValue: Specifies the sequences minimum value.
No MinValue: It specifies a minimum value of 1 for an ascending sequence.
MaxValue: Specifies a maximum value that a sequence can be generated.
No MaxValue: Specifies a maximum of 1027 for an ascending sequence or -1 for a
descending sequence. This is default clause.
StartWith: Specifies the first sequence number to be generated. The default for an
ascending sequence is the sequence minimum value and for descending, it is the
maximum value.
Cycle: This specifies that the sequence continues to generate values after reaching its
maximum or minimum value.
NoCycle: Specifies that a sequence can’t generate more values after reaching
maximum or minimum value.
Control structure available in PL/SQL
As other programming language we also have control statement in PL/SQL
through we can change the sequential flow of control i.e., commands to control the
flow of program execution. They make the difference, analyzing condition and
allowing decisions to be made within the program. The control structures can be
divided as:
1. Conditional controls
2. Unconditional controls
3. Sequential controls
4. Repetition controls
Condition Controls: Based on value of particular variable decision is taken which
statement is to be executed. The following are the condition controls available in
PL/SQL:

DBMS Page 20
IF…THEN Command: The purpose of the If..Then command is to evaluate a
condition and execute one or more command lines only if the condition analyze is
true. The If..Then command has two variations.
Syntax: IF <condition> THEN
Statements
END IF;
The commands found after the THEN and END IF clauses are executed only if the
condition is true.
IF- ELSE ladder Command:
In this structure, more than one condition may be analyzed and consequently several
action executed.
Syntax:
IF <condition> THEN
Statements
ELSIF <condition> THEN
Statements
ELSIF <condition> THEN
Statements
……………………………
……………………………
…………………………..
ELSE
Statements
END IF;
In this structure we can have numerous ELSIF clauses, but may have
only one ELSE clause. In this structure if the main condition returns False, the first
ELSIF clause is analyzed. If it is TRUE, the next commands are executed until
another ELSIF or ELSE clause is found. If the first ELSIF condition is FALSE, the
program tests the second, and so forth. Upon finding the first TRUE condition, it
executes its command and continues the program after the END IF command line. An
IF…THEN command may be nested within other IF.THEN commands.
LOOP command:
The LOOP command executes a group of command indefinitely or until some
condition forces breaking out of the loop and long program execution elsewhere. The

DBMS Page 21
LOOP command is used with EXIT command, which is responsible for stopping
execution of the loop.
Syntax:
LOOP
Body of the loop;
END LOOP;
Each time a the commands within a loop are executed, the cycle is restarted at
the command immediately after the LOOP command. Upon executing an EXIT
command control of execution passes to the line following that of the END LOOP
command.
FOR..LOOP Command:
The FOR..LOOP command is a variation of the LOOP command. Here the
commands are executed automatically until an evaluated condition returns false.
Syntax:

FOR <counter variable> IN [REVERSE]<initial_value>..<final_value>


LOOP
Body of the loop;
END LOOP;
WHILE Command: Another possible execution is the use of the WHILE
command. This structure analyze a condition only if it is TRUE are the commands
contained within the structure executed.
Syntax
WHILE <condition>
LOOP
Body of the loop;
END LOOP;
GOTO Command: The GOTO command allows you to change the flow of control
with in PL/SQL block. The entry point of a block is defined with in two less than <<
and two greater than >> symbols.
Syntax:
<<label_name>>
Statements;
IF <condition> THEN
GOTO <lable_name>;

DBMS Page 22
END IF;

cursors in sql
A cursor is a special construct used in procedural SQL to hold the data rows returned
by an SQL to hold the data tows returned by an SQL query. A cursor is a reserved
area of memory in which the output of the query is stored like an array holding
columns and rows. There are two types of cursor:
1. Implicit Cursor: An implicit cursor is automatically created in procedural SQL
when the SQL statement returns only one value. Oracle implicitly opens a cursor to
process each SQL statement not associated with an explicitly declared cursor.
2. Explicit Cursor: An explicit cursor is created to hold the output of an SQL
statement that may return two or more rows.
Database cursors enable you to select a group of data, scroll through the group of
records and examine each individual line of data as the cursor points to it.
Follow these steps to create, use, and close a database cursor:
1. Create the cursor.
2. Open the cursor for use within the procedure or application.
3. Fetch a record's data one row at a time until you have reached the end of the
cursor's records.
4. Close the cursor when you are finished with it.
5. Deallocate the cursor to completely discard it.
Creating a Cursor
To create an explicit cursor, we use the following syntax:
CURSOR cursor_name IS SQL statement;
For example: Declare
CURSOR csr_stud IS Select sno, sname, savg FROM student ;
Opening a Cursor:
Opening a cursor execute the query and identifies the active set that contains
all the rows which need the query search criteria.
Syntax : OPEN cursor_name;
Eg: Begin
Open csr_stud;
End;
Fetching a Record from the Cursor:

DBMS Page 23
The fetch statement retrieves the rows from the active set to the variables one
at a time. We can make use of any loop structure like Loop..End Loop, While, For
etc., to fetch the records from the cursor into variables one row at a time.
Syntax: Fetch cursor_name INTO var1, var2, ……….varN;
For each column value returned by the query associated cursor, there must be
corresponding variable in the into list and there data types must match. These variable
must be declared in the declare section of the PL/SQL block.
Eg:
LOOP
FETCH csr_stud into csno,csname,csavg;

Dbms_output.put_line(csno||csname||csavg);
END LOOP;
Closing a Cursor:
The close statement Tables the cursor and the active set becomes undefined.
This will release the memory occupied by the cursor and its data set. Once a cursor is
close, the user can re-open the cursor using the open statement.
Syntax: close cursor_name;

DBMS Page 24

You might also like