0% found this document useful (0 votes)
17 views30 pages

DBMS - Iv Unit

Bachelor of computer science dbms full sem units

Uploaded by

b13261344
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)
17 views30 pages

DBMS - Iv Unit

Bachelor of computer science dbms full sem units

Uploaded by

b13261344
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/ 30

DATABASE MANAGEMENT SYSTEM

UNIT IV

2 marks:
1. Give two advantages of PL/SQL over SQL.
• There are no variables in SQL whereas PL/SQL has variables constraints, data
types, etc.
• PL/SQL offers high processing speed while performing manipulation of large
volumes of data. This can’t be achieved with SQL.

2.Give the structure of PL/SQL program.


[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
/
3. When is declare statement is needed in PL/SQL?
Ans: The declaration section is required if any variables are to be used in a PL/SQL block.
The declaration section also defines cursors, types, local procedures, and functions that are
used in a block. If no variables or other elements need to be declared, then this section may
be omitted.
4. What is literal in PL/SQL? Mention two types of literals.
A literal is an explicit numeric, character, string, or Boolean value not represented by an
identifier. For example, TRUE, 786, NULL, 'tutorialspoint' are all literals of type Boolean,
number, or string. PL/SQL, literals are case-sensitive. Two types of literals are:
1. Integer literals
2. String literals
5. Differentiate % TYPE and % ROWTYPE variables.
• %TYPE provides the data type of a variable or a database column to that variable.
• %ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.
6. What is oracle transaction?
A transaction is a logical, atomic unit of work that contains one or more SQL statements. A
transaction groups SQL statements so that they are either all committed, which means they are
applied to the database, or all rolled back, which means they are undone from the database.
7. What is the purpose of commit command.
COMMIT is a transaction control language in SQL. It lets a user permanently save all the
changes made in the transaction of a database or table. Once you execute the COMMIT, the
database cannot go back to its previous state in any case.

8. Give the general format of while loop construct in PL/SQL.


WHILE condition LOOP
sequence_of_statements
END LOOP;
Eg: DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
9. Give the syntax of for loop construct in PL/SQL
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
10. What is use of ROLLBAK command?
ROLLBACK tells Oracle to roll back the entire transaction. In your case, both the INSERT and
the DELETE are part of the same transaction so the ROLLBACK reverses both operations. That
returns the database to the state it was in immediately following the CREATE TABLE statement.
Some alternatives:
If you were to issue a COMMIT after the INSERT then the DELETE statement would be in a
separate transaction and the ROLLBACK would reverse only the effect of the DELETE
statement.
You could also create a savepoint after running the INSERT statement and then rollback to that
savepoint after the DELETE rather than rolling back the entire transaction.
11. What is the use of SAVE POINT in oracle transaction?
A simple rollback or commit erases all savepoints. When we roll back to a savepoint, any
savepoints marked after that savepoint are erased. The savepoint to which we roll back remains.
We can reuse savepoint names within a transaction. The savepoint moves from its old position to
the current point in the transaction.
If we mark a savepoint within a recursive subprogram, new instances of the SAVEPOINT
statement are executed at each level in the recursive descent. You can only roll back to the most
recently marked savepoint.
An implicit savepoint is marked before executing an INSERT, UPDATE, or DELETE statement.
If the statement fails, a rollback to the implicit savepoint is done. Normally, just the failed SQL
statement is rolled back, not the whole transaction.
12. Give the syntax of SELECT statement in PL/SQL.
The syntax for the SELECT statement in Oracle/PLSQL is:
SELECT expressions
FROM tables
[WHERE conditions];
13. What is cursor?
A cursor is a named control structure used by an application program to point to and select a row
of data from a result set. Instead of executing a query all at once, you can use a cursor to read and
process the query result set one row at a time. A cursor in a PL/SQL context is treated as a WITH
HOLD cursor.

14. Differentiate implicit and explicit cursors.

Implicit Cursors Explicit Cursors


Implicit cursors are automatically created Explicit cursors needs to be defined explicitly by
when select statements are executed. the user by providing a name.
They are capable of fetching a single row at a
Explicit cursors can fetch multiple rows.
time.
Closes automatically after execution. Need to close after execution.
They are more vulnerable to errors such as They are less vulnerable to errors(Data errors
Data errors, etc. etc.)
Provides less programmatic control to the
User/Programmer has the entire control.
users
Comparative to Implicit cursors, explicit cursors
Implicit cursors are less efficient.
are more efficient.

15. List four cursor attributes.


1. %FOUND Attribute
2. %ISOPEN Attribute
3. %NOTFOUND Attribute
4. %ROWCOUNT Attribute

16. Give the general format of defining explicit cursor.


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

17. What is the command used to read the cursor data? Give syntax.

DECLARE CURSOR Command


The DECLARE command is one of four commands used in cursor processing, along with FETCH, OPEN, and
CLOSE.
18. Differentiate between cursor with parameters and without parameters.
Parameterized Cursor : A cursor can take parameters, which can appear in the associated query
wherever constants can appear.Parameterized cursors can only reference its own parameters.
Parameterized cursors cannot reference local variables.
19. What is an exception? How it is handled in PL/SQL?
An exception is a PL/SQL error that is raised during program execution. either implicitly by
TimesTen or explicitly by your program.
How to handle :
• Predefined TimesTen error : One of approximately 20 errors that occur most often in
PL/SQL code. You are not required to declare these exceptions. They are predefined by
TimesTen. TimesTen implicitly raises the error.
• Non-predefined TimesTen error : Any other standard TimesTen error. These must be
declared in the declarative section of your application. TimesTen implicitly raises the
error and you can use an exception handler to catch the error.
• User-defined error : Error defined and raised by the application. These must be declared in
the declarative section. The developer raises the exception explicitly.
20. List any two oracle named exceptions.
INVALID_NUMBER ORA01722
STORAGE_ERROR ORA-06500
PROGRAM_ERROR ORA-06501
21. What is difference between function and stored procedure?
Function Stored Procedure
Used mainly to perform some calculation. Used mainly to a execute certain process.
It is mandatory to return the value. It is not mandatory to return the value.
Can have only input parameters for it. Can have input or output parameters.
Functions can be called from Procedure. Procedures cannot be called from a
Function.
22. Give the syntax of defining stored procedure in Pl/SQL.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments –
CREATE PROCEDURE procedure_name
=,
=,
=
AS
BEGIN
-- Query –
END
GO
23. Give the syntax of defining function in Pl/SQL.
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

24. Differentiate between IN and OUT parameters of procedure/function.


• Main difference between IN and OUT parameters is that IN is used to pass data to the
database via SQL query, while OUT parameter is used to read results from the database,
especially in the case of stored procedure.
• Second difference is that the value of IN paraemter is provided using setXXX() mehtod like
the setString(), setInt(), while value of OUT parameter is retrieved using getXXX() method
like the getString(), getInt() etc.

25. Mention two advantages of using PACKAGE in Oracle.


• Allows us to overload the queries.
• Improves the performance of the applications.
• Promotes code reusability.

26. What are the components of oracle package?


Packages consist of two main components: the package specification and the package body.
• The package specification is the public interface, comprising the elements that can be
referenced outside of the package. A package specification is created by executing the
CREATE PACKAGE statement.
• The package body contains the actual implementation of all of the procedures and functions
that are declared within the package specification, as well as any declaration of private types,
variables, and cursors. A package body is created by executing the
CREATE PACKAGE BODY statement.
27. Give the general format of PACKAGE specification.
Package specification consists of a declaration of all the public variables, cursors, objects,
procedures, functions, and exception.
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
END <package name>

28. Give the General format of PACKAGE body.


It consists of the definition of all the elements that are present in the package specification. It can
also have a definition of elements that are not declared in the specification .
CREATE [OR REPLACE] PACKAGE BODY <package_name>
IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization>
END <package_name>

29. What the package used to display the message on the screen? Give Syntax.
The DBMS_OUTPUT is a built-in package that enables you to display output, debugging
information, and send messages from PL/SQL blocks, subprograms, packages, and triggers.

Syntax:

Dbms_output.put_line(‘Hello Reader!’);.

Output: Hello Reader!


3 or more marks

1. Explain structure of PL/SQL program with example.


PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are
different sections of PL/SQL blocks.

1. Declaration section
2. Execution section
3. Exception-Handling section

The below picture illustrates the different PL/SQL block and their section order.

Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section
in which the declaration of variables, cursors, exceptions, subprograms, pragma instructions and
collections that are needed in the block will be declared. Below are few more characteristics of
this part.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is written
inside it. Since the PL/SQL expects the executable statements from this block this cannot be an
empty block, i.e., it should have at least one valid executable code line in it.
Below are few more characteristics of this part.
Exception-Handling Section
The exception is unavoidable in the program which occurs at run-time and to handle this Oracle
has provided an Exception-handling section in blocks. This section can also contain PL/SQL
statements. This is an optional section of the PL/SQL blocks.

Example:
2. What are different types of literals? Explain with example.

SQL Literals
There are four kinds of literal values supported in SQL. They are : Character string, Bit string,
Exact numeric, and Approximate numeric. These are explained as following below.

1. Character string :
Character strings are written as a sequence of characters enveloped in single quotes.
the only quote character is delineate at intervals a personality string by 2 single quotes. Some
example of character strings are : ‘My String’ , ‘I love GeeksForGeeks’ , ‘16378’

2. Bit string :
A bit string is written either as a sequence of 0s and 1s enveloped in single quotes and
preceded by the letter ‘B’ or as a sequence of positional representation system digits
enveloped in single quotes and preceded by the letter X’ some examples are given below :
 B’10001011′
 B’1′
 B’0′
 X’C 5′
 X’0′
3. Exact numeric :
These literals ar written as a signed or unsigned decimal variety probably with
mathematical notation. Samples of actual numeric literals are given below :
 8
 80.00
 +88.88
 -88.88
4. Approximate numeric :
Approximate numeric literals are written as actual numeric literals followed by the letter ‘E’,
followed by a signed or unsigned number. Some example are :
 6E6
 66.6E6
 +66E-6
 -6.66E-8

3. Explain the syntax and usage of the following with example.


a) While loop. B) for loop. C)if... end if

PL/SQL While Loop


PL/SQL while loop is used when a set of statements has to be executed as long as a condition is
true, the While loop is used. The condition is decided at the beginning of each iteration and
continues until the condition becomes false.

Syntax of while loop: WHILE <condition>


LOOP statements;
END LOOP;
Example
DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;

PL/SQL - FOR LOOP Statement


A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
• The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
• Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body
of the loop is executed. If it is FALSE, the body of the loop does not execute and the flow
of control jumps to the next statement just after the for loop.
• After the body of the for loop executes, the value of the counter variable is increased or
decreased.
• The condition is now evaluated again. If it is TRUE, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes FALSE, the FOR-LOOP terminates.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/

IF...ELSE STATEMENT:-
The IF statement associates a condition with a sequence of statements enclosed by the keywords
THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is
FALSE or NULL, then the IF statement does nothing.
Syntax
IF condition THEN
{...statements to execute when condition is TRUE...}
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
Example:
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
IF( a < 20 ) THEN
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
If the Boolean expression condition evaluates to true, then the block of code inside the if statement
will be executed. If the Boolean expression evaluates to false, then the first set of code after the
end of the if statement (after the closing end if) will be executed.

4. Write a note on labelled loops.


Loop Labels
You can give a name to a loop by using a label. A loop label in PL/SQL has the following
format:
<<label_name>>
where label_name is the name of the label, and that loop label appears immediately before the
LOOP statement:
<<all_emps>>
FOR emp_rec IN emp_cur
LOOP
...
END LOOP;
The loop label is potentially useful in several ways:
• When you have written a loop with a large body, use a loop label to tie the end of the loop
back explicitly to its start. This visual tag will make it easier for a developer to maintain and
debug the program. Without the loop label, it can be very difficult to keep track of which
LOOP goes with which END LOOP.
• You can use the loop label to qualify the name of the loop indexing variable (either a
record or a number). Again, this can be helpful for readability. Here is an example:
<<year_loop>>
FOR year_number IN 1800..1995
LOOP
<<month_loop>>
FOR month_number IN 1 .. 12
LOOP
IF year_loop.year_number = 1900 THEN ... END IF;
END LOOP month_loop;
END LOOP year_loop
• When you have nested loops, you can use the label both to improve readability and to
increase control .
5. Explain the commit and rollback commands used in oracle transaction with example.
A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the
statements should execute successfully or none of the statements should execute.

To control transactions Oracle does not made permanent any DML statements unless you commit
it. If you don’t commit the transaction and power goes off or system crashes then the transaction
is roll backed.

COMMIT
To make the changes done in a transaction permanent issue the COMMIT statement.
Syntax:
COMMIT [WORK] [COMMENT ‘your comment’];

WORK is optional.
COMMENT is also optional, specify this if you want to identify this transaction in data
dictionary DBA_2PC_PENDING.
Example: insert into emp (empno,ename,sal) values (101,’Abid’,2300);
commit;

ROLLBACK
To rollback the changes done in a transaction give rollback statement. Rollback restore the state
of the database to the last commit point.
Example :
delete from emp;
rollback; /* undo the changes */
6. What is a cursor ? Explain different types of cursor.

Cursor is a Temporary Memory or Temporary Work Station. Whenever DML statements are
executed, a temporary work area is created in the system memory. A cursor can have more than
one row, but processing wise only 1 row is taken into account. They can be used well with DML
statements like Update, Insert and Delete. In PL/SQL, two different types of cursors are available.
In PL/SQL, two different types of cursors are available.
(i) Implicit cursors
(ii) Explicit cursors

Explicit cursors
Explicit cursors are defined by the programmers to have more control area on the context area.
It has to be defined in the declaration section of the PL/SQL Block. Usually, It is defined on a
SELECT Statement and it returns more than one row as output. We can iterate over the rows of
data and perform the required operations.

Syntax:
CURSOR cursor_name IS select_statement;
Steps involved in creating explicit cursors:
• Cursor Declaration for initializing the memory
CURSOR <cursorName> IS
SELECT <Required fields> FROM <tableName>;
• Cursor Opening to allocate the memory
OPEN <cursorName>;
• Cursor Fetching to retrieve the data
FETCH <cursorName> INTO <Respective columns>
• Cursor Closing to release the allocated memory
CLOSE <cursorName>;

Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || '
' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Implicit Cursors

The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if you
don't use an explicit cursor for the statement.These are created by default to process the statements when
DML statements like INSERT, UPDATE, DELETE etc. are executed.

Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.

Let's execute the following program to update the table and increase salary of each customer by
5000.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers
updated ');
END IF;
END;
/
7. Explain use of parameterised cursor with example.
Parameterized cursor pass the parameters into a cursor and use them in to query. An explicit
cursor may accept a list of parameters. Each time you open the cursor, you can pass different
arguments to the cursor, which results in different result sets.
Syntax:
CURSOR cursor_name (parameter_list)
IS
cursor_query;

In the cursor query, each parameter in the parameter list can be used anywhere which a constant is used.
The cursor parameters cannot be referenced outside of the cursor query.
To open a cursor with parameters, you use the following syntax:
OPEN cursor_name (value_list);

Example:

DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/
Output:
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k

8. Explain with syntax and example, how to create a cursor and read the records from a
cursor.
Cursors can be explicitly created on a SELECT Statement which returns more than one row.
Syntax:
CURSOR cursor_name IS select_statement;

Steps involved in creating explicit cursors:


• Cursor Declaration for initializing the memory
CURSOR <cursorName> IS
SELECT <Required fields> FROM <tableName>;
• Cursor Opening to allocate the memory
OPEN <cursorName>;
• Cursor Fetching to retrieve the data
FETCH <cursorName> INTO <Respective columns>
• Cursor Closing to release the allocated memory
CLOSE <cursorName>;
Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || '
' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/

9. Explain all the attributes of a cursor.


Each cursor has a set of attributes that enables an application program to test the state of the
cursor. These attributes are %ISOPEN, %FOUND, %NOTFOUND, and %ROWCOUNT.
This attribute is used to determine whether a cursor is in the open state.
%FOUND Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. Before the
first fetch from an open cursor, cursor_name%FOUND returns NULL. Afterward, it returns
TRUE if the last fetch returned a row, or FALSE if the last fetch failed to return a row.

host_cursor_variable_name
A cursor variable declared in a PL/SQL host environment and passed to PL/SQL as a bind
variable. The datatype of the host cursor variable is compatible with the return type of any
PL/SQL cursor variable. Host variables must be prefixed with a colon.

%ISOPEN Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. If a cursor is
open, cursor_name%ISOPEN returns TRUE; otherwise, it returns FALSE.

%NOTFOUND Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. Before the first
fetch from an open cursor, cursor_name%NOTFOUND returns NULL. Thereafter, it returns
FALSE if the last fetch returned a row, or TRUE if the last fetch failed to return a row.

%ROWCOUNT Attribute
A cursor attribute that can be appended to the name of a cursor or cursor variable. When a cursor
is opened, %ROWCOUNT is zeroed. Before the first
fetch, cursor_name%ROWCOUNT returns 0. Thereafter, it returns the number of rows fetched
so far. The number is incremented if the latest fetch returned a row.
10. Write a note on error handling in PL/SQL.

In PL/SQL, an error condition is called an exception. Exceptions can be internally defined (by the
runtime system) or user defined. Examples of internally defined exceptions include division by
zero and out of memory.

When an error occurs, an exception is raised. That is, normal execution stops and control
transfers to the exception-handling part of your PL/SQL block or subprogram. Internal
exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions
must be raised explicitly by RAISE statements, which can also raise predefined exceptions.
To handle raised exceptions, you write separate routines called exception handlers. After an
exception handler runs, the current block stops executing and the enclosing block resumes with
the next statement. If there is no enclosing block, control returns to the host environment.

Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is
the simple syntax for raising an exception −

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;

Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT
INTO statement returns no rows.

11. Explain any three system exceptions of PL/SQL.


There are 3 types of Exceptions.
a) Named System Exceptions/ Defined system exceptions
b) Unnamed System Exceptions/Undefined system exceptions
c) User-defined Exceptions
a) Named System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
There are some system exceptions which are raised frequently, so they are pre-defined and given
a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code
to handle the exception as given below.
BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;

b) Unnamed System Exceptions


Those system exception for which oracle does not provide a name is known as unnamed system
exception. These exception do not occur frequently. These Exceptions have a code and an
associated message.
There are two ways to handle unnamed system exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined
exception name.
The general syntax to declare unnamed system exception using EXCEPTION_INIT is:
DECLARE
exception_name EXCEPTION;
PRAGMA
EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
handle the exception
END;
Example:
DECLARE
Child_rec_exception EXCEPTION;
PRAGMA
EXCEPTION_INIT (Child_rec_exception, -2292);
BEGIN
Delete FROM product where product_id= 104;
EXCEPTION
WHEN Child_rec_exception
THEN Dbms_output.put_line('Child records are present for this
product_id.');
END; /
c) User-defined Exceptions
This type of users can create their own exceptions according to the need and to raise these
exceptions explicitly raise command is used.
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception
section.
Example:
DECLARE
x int:=&x; /*taking value at run time*/
y int:=&y;
div_r float;
exp1 EXCEPTION;
exp2 EXCEPTION;
BEGIN
IF y=0 then
raise exp1;
ELSEIF y > x then
raise exp2;
ELSE
div_r:= x / y;
dbms_output.put_line('the result is '||div_r);
END IF;
EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');
WHEN exp2 THEN
dbms_output.put_line('Error');
dbms_output.put_line('y is greater than x please check the input');
END;
/

12. What is a procedure/function? What are the advantages of procedures / functions?


A procedure or function is a schema object that logically groups a set of SQL and other PL/SQL
programming language statements together to perform a specific task. Procedures and functions
are created in a user's schema and stored in a database for continued use.
Advantages of procedures/functions:
1. Provides Reusability and avoids redundancy
• The same block of code for procedure or function can be called any number of times for
working on multiple data.
• Due to which number of lines of code cannot be written repeatedly.
2. Maintains Integrity
• Integrity means accuracy. Use of procedure or function ensures integrity because they are
stored as database objects by the oracle engine.
3. Maintains Security
• Use of stored procedure or function helps in maintaining the security of the database as
access to them and their usage can be controlled by granting access/permission to users
while the permission to change or to edit or to manipulate the database may not be
granted to users.
4. Saves Memory
• Stored procedure or function have shared memory. Due to which it saves memory as a
single copy of either a procedure or a function can be loaded for execution by any
number of users who have access permission.

13. Explain with example how to create a procedure / function and use it.
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.

Syntax for creating procedure:

CREATE [OR REPLACE] PROCEDURE procedure_name


[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];

In this example, we are going to insert record in user table. So you need to create user table first.

Table creation:
create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

create or replace procedure "INSERTUSER"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
/

Output: Procedure created.


14. Explain the keyword and parameters used for creating procedures/functions Ans:

• CREATE or REPLACE PROCEDURE is a keyword used for specifying the name of


the procedure to be created.

• BEGIN, EXCEPTION and END are keywords used to indicate different sections of
the procedure being created.

When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:

Based on their purpose parameters are classified as


1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter
IN Parameter:
• This parameter is used for giving input to the subprograms.
• It is a read-only variable inside the subprograms. Their values cannot be changed
inside the subprogram.
• In the calling statement, these parameters can be a variable or a literal value or an
expression, for example, it could be the arithmetic expression like ‘5*8’ or ‘a/b’
where ‘a’ and ‘b’ are variables.
• By default, the parameters are of IN type.

OUT Parameter:
• This parameter is used for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside
the subprograms.
• In the calling statement, these parameters should always be a variable to hold the
value from the current subprograms.
IN OUT Parameter:

• This parameter is used for both giving input and for getting output from the
subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside
the subprograms.
• In the calling statement, these parameters should always be a variable to hold the
value from the subprograms.

15. Explain different data types supported by PL/SQL.


Ans: Data Types in PL/SQL are used to define how the data will be stored, handled, and
treated by Oracle during the data storage and processing. Data types are associated with
the specific storage format and range constraints. In Oracle, each value or constant is
assigned with a data type. Following is the diagram of different Oracle PL/SQL Data
Types:
16. Explain various commands associated with oracle transaction with examples.
The following commands are used to control transactions.
• COMMIT − to save the changes.
• ROLLBACK − to roll back the changes.
• SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
• SET TRANSACTION − Places a name on a transaction.
Transactional Control Commands
Transactional control commands are only used with the DML Commands such as - INSERT,
UPDATE and DELETE only. They cannot be used while creating tables or dropping them
because these operations are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all the transactions to the database
since the last COMMIT or ROLLBACK command. The syntax for the COMMIT command is
as follows.
COMMIT;
Example: insert into emp (empno,ename,sal) values (101,’Abid’,2300);
commit;

The ROLLBACK Command


The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
Example :
delete from emp;
rollback; /* undo the changes */
The SAVEPOINT Command
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
Example:
SQL> ROLLBACK TO SP2;
Rollback complete.
The SET TRANSACTION Command
The SET TRANSACTION command can be used to initiate a database transaction. This
command is used to specify characteristics for the transaction that follows. For example, you
can specify a transaction to be read only or read write.
The syntax for a SET TRANSACTION command is as follows.
SET TRANSACTION [ READ WRITE | READ ONLY ];

17. Explain various forms of if...endif structures with syntax and example.
18. Explain various looping statements of PL/SQL with syntax.
19. Explain various commands/statements required to open , process and close the
explicit cursor with syntax and example.
The explicit cursor is programmer defined cursor which is used to process set of select
statements together.
Opening the Cursor
The OPEN statement of cursor will execute the query associated with the cursor. When you
use the OPEN statement following will happen :

•Dynamically allocates the memory for context area.


•It parses the select statement

•Binds the input variable

•Identifies the active set . The active set is set of rows which satisfies search criteria.

√It will position the pointer at first row.


Syntax:
Open Cursor_name; Example
:
Open C_Employee;
Fetching data from Cursor(Process):
The Fetch statement will fetch the rows from table once at a time. We can use the
%NOTFOUND attribute to determine the entire active set is being retrieved.
FETCH statement performs :

•It will read the data from current row.

•Advances the pointer to next row Fetch


Syntax :
FETCH Cursor_name from Variable_names;
Close the Cursor:
This is also the most important step where user can use the close cursor statement to release
the context area and closing the cursor. You can reopen the cursor if required. You should
make habit to close the cursor to free up the resources.
Syntax:
Close Cursor_name;
Example:
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
C_id customers.id%type;
C_name customers.name%type;
C_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
Dbms_output.put_line(c_id || ‘ ‘ || c_name || ‘ ‘ || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result –
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
20.Write a PL/SQL block to accept custno from the user and check whether there
are any rows matching the customer no. in the table
CUSTOMER(custid,custname,item,qty) . Accordinglyinsert a row in the table
operation on the following condition.

i) If no rwos are found -> ‘No rows found’.


ii) If more than one rows are found -> ‘Multiple rows found’. iii) If only one
row is found -> “One row found’.

21. With syntax and example explain how a stored procedure is created and executed in
PL/SQL ?
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
•Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
•Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
Executable_section
[EXCEPTION
Exception_section]
END [procedure_name];
Table creation:
Create table user(id number(10) primary key,name varchar2 *Now
write the procedure code to insert record in user table.
Procedure Code:

Create or replace procedure “INSERTUSER”


(id IN NUMBER,
Name IN VARCHAR2)
Is
Begin
Insert into user values(id,name);
End;
/
Output:
Procedure created.

22. With syntax and example explain how a function is created and executed in PL/SQL?
Ans: Function can be used as a part of SQL expression i.e. we can use them with
select/update/merge commands. One most important characteristic of a function is that,
unlike procedures, it must return a value.
Syntax: Creating a function
CREATE [OR REPLACE] FUNCTION function_name [parameters] [(parameter_name [IN
| OUT | IN OUT] type [, …])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body > END
[function_name]; Here:
Function_name: specifies the name of the function.[OR REPLACE] option allows modifying
an existing function.

•The optional parameter list contains name, mode and types of the parameters.
•IN represents that value will be passed from outside and OUT represents that this parameter
will be used to return a value outside of the procedure.
The function must contain a return statement:

•RETURN clause specifies that data type you are going to return from the function.

•Function_body contains the executable part.


•The AS keyword is used instead of the IS keyword for creating a standalone function.The
function must contain a return statement.
Example:
Create or replace function adder(n1 in number, n2 in number)
Return number
Is
N3 number(8);
Begin
N3 n1+n2;
Return n3;
End;
/
Now write another program to call the function:
DECLARE
N3 number(2);
BEGIN
N3 adder(11,22);

Dbms_output.put_line(‘Addition is: ‘ || n3);


END;
/
Output:
Addition is: 33
Statement processed.

23. With syntax and example explain how a package is created and executed in
PL/SQL?
A package is a way of logically storing the subprograms like procedures, functions, exception
or cursor into a single common unit.
create a PL/SQL Package
Following are the steps to declare and use a package in PL/SQL code block:
STEP 1: Package specification or declaration.
syntax:
CREATE OR REPLACE PACKAGE <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>)
RETURN <datatype>;
PROCEDURE <procedure_name> (<list of arguments>);

Code statements
END <package_name>; Where,

•CREATE OR REPLACE PACKAGE are keywords used to create a package


•FUNCTION and PROCEDURE are keywords used to declare function and procedure while
creating papackag
<package_name>, <function_name>, <procedure_name> are user-defined names.

•IS/AS are keywords used to declare package.


•RETURN is a keyword specifying value returned by the function declared.
STEP 2: Package Body
It mainly comprises of the following:
•It contains the definition of procedure, function or cursor that is declared in the package
specification.

•It contains the subprogram bodies containing executable statements for which package has
been created.
syntax:
CREATE OR REPLACE PACKAGE BODY <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>) RETURN <datatype>IS/AS

Local variable declaration;


BEGIN

Executable statements;
EXCEPTION
Error handling statements;
END <function_name>;
PROCEDURE <procedure_name> (<list of arguments>)IS/AS

Local variable declaration;


BEGIN

Executable statements;
EXCEPTION

Error handling statements;


END <procedure_name>;
END <package_name>;
Where,
•CREATE OR REPLACE PACKAGE BODY are keywords used to create the package with
a body.
•FUNCTION and PROCEDURE are keywords used to define function and procedure while
creating package.
<package_name>, <function_name>, <procedure_name> are user-defined.
•IS/AS are keywords used to define the body of package, function and procedure.
•RETURN is a keyword specifying value returned by the function defined.
•DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code block
containing variable declaration, executable statements, error handling statements and marking
end of PL/SQL block respectively where DECLARE and EXCEPTION part are optional.
Example:
CREATE PACKAGE teachers_sal AS
PROCEDURE find_sal(t_id teachers.id%type);
END teachers_sal;
/
Output: Package created

CREATE OR REPLACE PACKAGE BODY teachers_sal AS


PROCEDURE find_sal(t_id teachers.id%TYPE) IS
T_sal teachers.salary%TYPE;
BEGIN
SELECT salary INTO t_sal
FROM teachers
WHERE id = t_id;

Dbms_output.put_line(‘Salary: ‘|| c_sal);


END find_sal;
END teachers_sal;
/
Output:
Package body created.
Using the package elements
The package elements like variables, procedures or functions are accessed by the syntax
that is given below: Package_name.element_name; Example:
DECLARE
Code teachers.id%type &tt_id;
BEGIN
Teachers_sal.find_sal(code);
END;
/
Output:
Enter value for tt_id: 2
Salary: 3000
PL/SQL procedure successfully completed.
24. With example explain how user defined exception is handled in a PL/SQL program.
An error occurs during the program execution is called Exception in PL/SQL. These
errors/exceptions can be handled by using syntax:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
Exception1-handling-statements
WHEN exception2 THEN
Exception2-handling-statements
WHEN others THEN
Exception3-handling-statements
END;
Example:
Here we are using the already created CUSTOMERS table.
SELECT* FROM COUSTOMERS;

DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

After the execution of above code at SQL Prompt, it produces the following result:

The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
runtime exception NO_DATA_FOUND, which is captured in EXCEPTION block.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy