rdbms - pl sql - topic 5 - msbte questions and · pdf filesection to handle errors. end...

31
RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS SUMMER 2017 Q. Describe Exception handling. Explain with example. 4 Marks Exception Handling: Exception is nothing but an error. Exception can be raise when DBMS encounters errors or it can be raised explicitly. When the system throws a warning or has an error it can lead to an exception. Such exception needs to be handled and can be defined internally or user defined. Exception handling is nothing but a code block in memory that will attempt to resolve current error condition. Syntax: DECLARE ; Declaration section …executable statement; EXCEPTION WHEN ex_name1 THEN :Error handling statements/user defined action to be carried out; END; DECLARE s_rollNostudents.rollNo%type := 10; s_namestudents.name%type; s_addressstudents.address%type; BEGIN SELECT rollNo, name, address FROM students WHERE rollNo = s_rollNo; dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' || s_address); EXCEPTION WHEN no_data_found THEN dbms_output.put_line('No such student!'); WHEN others THEN dbms_output.put_line('Error!'); END; Q. Write a PL/SQL program to print numbers from 50 to 60 using for loop. 4 Marks (Note: Any other Logic also considered) DECLARE x number :=50; BEGIN

Upload: lytuyen

Post on 25-Feb-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS

SUMMER 2017

Q. Describe Exception handling. Explain with example. 4 Marks

Exception Handling: Exception is nothing but an error. Exception can be raise when DBMS

encounters errors or it can be raised explicitly. When the system throws a warning or has an error

it can lead to an exception. Such exception needs to be handled and can be defined internally or

user defined. Exception handling is nothing but a code block in memory that will attempt to

resolve current error condition.

Syntax:

DECLARE

; Declaration section

…executable statement;

EXCEPTION

WHEN ex_name1 THEN

:Error handling statements/user defined action to be carried

out;

END;

DECLARE

s_rollNostudents.rollNo%type := 10;

s_namestudents.name%type;

s_addressstudents.address%type;

BEGIN

SELECT rollNo, name, address FROM students WHERE rollNo =

s_rollNo; dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' ||

s_address);

EXCEPTION

WHEN no_data_found THEN

dbms_output.put_line('No such student!');

WHEN others THEN

dbms_output.put_line('Error!');

END;

Q. Write a PL/SQL program to print numbers from 50 to 60 using for loop. 4 Marks

(Note: Any other Logic also considered)

DECLARE

x number :=50;

BEGIN

Page 2: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

LOOP

dbms_output.put_line(x);

x := x +1;

IF x >60 THEN

exit;

END IF;

END LOOP;

END;

Q. Explain implicit and explicit cursor. 4 Marks

Implicit Cursor:

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,

when there is no explicit cursor for the statement. Whenever a DML statement (INSERT,

UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For

INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and

DELETE operations, the cursor identifies the rows that would be affected.

In PL/SQL, implicit cursor as has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and

%ROWCOUNT.

Example of implicit cursor:

Begin

Update emp set salary= salary +500 where empno =&empno;

If SQL%FOUND then

Dbms_out.put_line(―Emp table modified‖);

Else

Dbms_out.put_line(―Emp table modified‖);

End if;

End;

Explicit cursor:

Explicit cursors are programmer defined cursors for gaining more control over the context area.

An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created

on a SELECT Statement which returns more than one row.

Working with an explicit cursor involves four steps:

Declaring the cursor for initializing in the memory

Cursor cursor_name IS select_statement;

Opening the cursor for allocating memory

Open cursorname;

Fetching the cursor for retrieving data

Fetch cursorname INTO variable1,variable2…

Page 3: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Closing the cursor to release allocated memory

Close cursorname;

Example of explicit cursor:

Declare

Cursor c1 is select empno, salary from emp Where deptno=10;

ecode emp.empno%Type;

sal emp.salary%Type;

Begin

Open c1;

If c1%ISOPEN then

Loop

Fetch c1 into ecode,sal;

If c1% NOTFOUND then Exit;

End if;

Update emp set salary = salary+500;

End Loop;

Close c1;

Else dbms_out.put_line(―unable to open‖);

End if;

End;

Q. Differentiate between view and index. 4 Marks

Page 4: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Q. Explain the concept of trigger. 4 Marks

A trigger is a PL/SQL block structure which is fired when DML statements like Insert, Delete,

Update is executed on a database table.

A trigger is triggered automatically when an associated DML statement is executed.

Syntax for Creating a Trigger:

CREATE OR REPLACE TRIGGER trigger_name

[BEFORE/AFTER]

[INSERT/UPDATE/DELETE]

ON Table_name [FOR EACH STATEMENT/FOR EACH ROW]

[WHEN CONDITION]

PL/SQL block

Example:

CREATE OR REPLACE TRIGGER trg1

BEFORE INSERT ON EMP

FOR EACH ROW

BEGIN

IF :new.sal<=0 THEN

Rasie_application_error(„Salary should be greater than 0‟);

END IF;

END;

Q. Define following term with example. 4 Marks

(i) Procedure

(ii) Function

(i) Procedure:

Definition: A procedure is named PL/SQL block which perform one or more specifies task.

Example

The following example creates a simple procedure that displays the string 'Hello World!' on the

screen when executed.

CREATE OR REPLACE PROCEDURE greetings

AS

BEGIN

dbms_output.put_line('Hello World!');

END;

(ii) Function:

Definition: Function is a logically grouped set of SQL and Pl/SQL statements that perform a

specific task.

Page 5: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Example:

This function returns the total number of CUSTOMERS in the customers table.

CREATE OR REPLACE FUNCTION totalCustomers

RETURN number IS

total number(2):=0;

BEGIN

SELECT count(*)into total

FROM customers;

RETURN total;

END;

/

Q. Explain GOTO statement with example. 4 Marks

The GOTO statement transfers control to a labelled block or statement.

It is an unconditional branching statement.

It does not use any condition for transferring the control to other part of code.

It transfers the control to the part of code which contains same label mentioned in goto

statement.

Syntax :

GOTO label;

..

..

<< label >>

statement;

Example :

DECLARE

p VARCHAR2(30);

n PLS_INTEGER := 37;

BEGIN

FOR j in 2..ROUND(SQRT(n)) LOOP

IF n MOD j = 0 THEN

p := ' is not a prime number';

GOTO print_now;

END IF;

END LOOP;

p := ' is a prime number';

<<print_now>>

DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);

END;

Page 6: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Q. Explain PL/SQL block structure. 4 Marks

Block structure of PL/SQL:

Declare

Declaration of memory variables

BEGIN (Mandatory)

SQL executable statements

Exception

Handling errors

END; (Mandatory)

A block begins with a declarative section where variables are declared. This is followed by a

section containing the procedural statements surrounded by BEGIN and END keywords.

Each block must have Begin and End statements and may optionally include an exception

section to handle errors. End section marks the end of PLSQL block.

Q. Explain locking strategy in detail. 4 Marks

Implicit Locking:

Implicit locks are generally placed by the DBMS automatically.

Explicit Locking:

The technique of lock taken on a table or its resources by a user is

called Explicit Locking.

Users can lock tables they own or any tables on which they have been

granted table privileges (such as select, insert, update, delete).

Explicit locking done by two ways as

1) The Select........For Update statement

It is used for acquiring exclusive row level locks in anticipation of

performing updates on records.

2) Using lock table statement:

To manually override Oracle‟s default locking strategy by creating a

data lock in a specific mode.

Syntax:

LOCK TABLE <TableName> [, <TableName>]…

IN { ROW SHARE| ROW EXCLUSIVE|SHARE

UPDATE|SHARE|SHARE ROW EXCLUSIVE|EXCLUSIVE}

[NOWAIT]

Page 7: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

SUMMER 2016

Q. Give any four advantages of using PL/SQL. 4 Marks

(Any four advantages - 1 mark each)

Advantages of PL/SQL:

1. PL/SQL is portable and high transaction processing language.

2. PL/SQL is in fact procedural language but it also supports object oriented programming.

3. PL/SQL is that development tool which not only supports SQL data manipulations but also

provides facilities of conditional checking and looping.

4. It allows user to write as well as access the functions and procedures from outside the programs.

5. It has got built in libraries of packages.

6. PL/SQL is highly productive as it works with the oracle forms to develop the application software

i.e. it works with the front ends to develop the complete commercial applications.

7. The performance of PL/SQL is better, as in single line query entire block of statements can be

processed.

8. Some special features of PL/SQL include the different data types that are capable of handling

different types of data required in real life applications.

9. The most important features like triggers, cursors, locks etc have made PL/SQL a very versatile

language.

10. Security can be ensured with the help of PL/SQL, while developing a commercial database

system.

11. PL/SQL is a user friendly language and very simple to use.

Q. What are Predefined exceptions and User defined exceptions? 4 Marks

(Predefined exception - 2 marks; User Defined exception - 2 marks)

1) Predefined Exception/system defined exception/named exception:

Are always automatically raised whenever related error occurs. The most common errors that can

occurs during the execution of PL/SQL. Not declared explicitly. I.e. cursor already open, invalid

cursor, no data found, zero divide and too many rows etc. Programs are handled by system defined

Exceptions.

2) User defined exception:

It must be declare by the user in the declaration part of the block where the exception is used. It is

raised explicitly in sequence of statements using: Raise_application_error (error_no,

error_name);

Q. What is lock? Explain types of locks. 4 Marks

(Lock - 2 marks; Description - 1 mark each type)

The lock table statement allows explicitly acquire a shared or exclusive table lock on the specified

table. The table lock lasts until the end of the current transaction. To lock a table, one must either be

Page 8: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

the database owner or the table owner. Syntax: LOCK TABLE TABLE-NAME IN {SHARED |

EXCLUSIVE} MODE; Types of Locks: Shared Lock Exclusive Lock.

1. Shared. If a transaction Ti has obtained a shared-mode lock (denoted by S) on item Q, then Ti

can read, but cannot write, Q. Shared Lock is provided to the readers of the data. These locks enable

all the users to read the concurrent data at the same time, but they are not allowed to change/ write

the data or obtain exclusive lock on the object. It could be set for table or table row. Lock is released

or unlocked at the end of transaction.

2. Exclusive. If a transaction Ti has obtained an exclusive-mode lock (denoted by X) on item Q, then

Ti can both read and write Q. Exclusive Lock is provided to the writers of the data. When this lock is

set on a object or transaction, it means that only writer, who has set the lock can change the data, and

if other users cannot access the locked object. Lock is released at the end of change in transaction.

Q. Write a PL/SQL program to find the square of a number given by user

usingWHILE….LOOP.(accept the number from user dynamically) 4 Marks

(Correct Program - 4 marks) [**NOTE: any relevant program logic shall be considered**]

SET SERVEROUTPUT ON;

DECLARE n number:= &n;

sqr number:= 0;

n_cntr number:=0;

BEGIN

DBMS_OUTPUT.PUT_LINE(n);

WHILE n_cntr < n LOOP

sqr:= sqr + n;

n_cntr := n_cntr + 1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Square of ' || n || ' is ' || sqr);

END;

Q. Write a PL/SQL program using while loop to display n even numbers. 4 Marks

(Correct logic - 2 marks; correct syntax - 2 marks) [** Note: Any relevant logic can be

considered**]

SET SERVEROUTPUT ON;

DECLARE n number:= &n;

i number:= 0;

cnt number:=0;

BEGIN

WHILE (cnt< n) LOOP

if( mod (i,2)=0) then

Page 9: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Dbms_output.put_line(i);

cnt:=cnt+1;

End if;

i:=i+1;

END LOOP;

END;

Q. List out any four statements of PL/SQL. 4 Marks

(Any four statement list/syntax - 1 mark each)

1. Declare

2. Begin

3. End

4. Exception

5. dbms_output.put_line();

6. If condition then

Statements Else Statements End if;

7. LOOP

<loop_body> END LOOP;

8. LOOP

<loop_body>

EXIT WHEN (condition); END LOOP;

9. WHILE <condition> LOOP

<loop body> END LOOP;

10. GOTO <<label_name>>;

11. FOR COUNTER IN [reverse] LOWER_BOUND..UPPER_BOUND LOOP

<loop body> END LOOP;

12. CASE [expression]

WHEN condition_1 THEN

result_1

WHEN condition_2 THEN

result_2 …..

WHEN condition_n THEN

result_N

ELSE

RESULT

END CASE;

Page 10: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Q. What is database trigger? Compare database triggers and procedures and explain the use

of database trigger.

(Definition - 1 mark; Comparison - 2 marks; Uses - 1 mark) [**Note: Any relevant comparison

can be considered**]

Database Trigger: Database trigger are ‗event-condition-action model„ which are fixed on certain

event. Trigger represents action to be taken if some event happens. In case of DBMS, triggers are

automatically fired when tables are modified with insert, update and delete etc.

Use of database trigger:

• Triggers can be used to prevent invalid transaction and to apply complex security authorization.

• It can be used to implement complicated integrity constraints.

• It can be used to maintain duplicate table and to check the data modifications.

Comparison:

Database Trigger Procedures

1. Triggers are fired when particular SQL

commands (DML) are executed

1. Procedures are executed when they are

called

2. Triggers have events and related actions 2. Procedure do not have events and related

actions

3. Triggers are called implicitly 3. Procedure are called explicitly

Q. Explain PL/SQL block structure. 4 Marks

(Correct Explanation - 4 marks)

A PL/SQL Block consists of four sections:

1. The Declaration section : Declaration of memory variables used later in begin section.

2. The Begin..End section : SQL executable statements for manipulating table data should be in

BEGIN....END block.

3. The Exception section : SQL and/or PL-SQL code to handle errors that may crop up during

execution of the above code block.

Page 11: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Q. List types of cursor and explain each with example. 4 Marks

(Description - 1 mark; example - 1 mark for each type; 1 mark shall be awarded if only list is

given) [**Note: any other examples showing use of implicit and explicit cursor can be

considered**]

Types of Cursor

Implicit cursor

Explicit cursor

Implicit cursor: If database engine opens a cursor for internal processing, it is called as implicit

cursor. Example of implicit cursor:

Declare

Begin

Update emp set salary= salary +500 where empno =&empno;

If SQL%FOUND then

Dbms_out.put_line(―Emp table modified‖);

Else Dbms_out.put_line(―Emp table modified‖);

End if;

End;

Explicit cursor: A user can open a cursor for processing data as required. Such user defined cursors

are known as explicit cursors.

Example of explicit cursor:

Declare

Cursor c1 is select empno, salary from emp Where deptno=10;

Ecode emp.empno%Type;

Sal emp.salary%Type;

Begin

Open c1;

If c1%ISOPEN then

Loop

Fetch c1 into ecode,sal;

If c1% NOTFOUND then

Exit;

End if;

Update emp set salary = salary+500;

End Loop;

Close c1;

Else

Dbms_out.put_line(―unable to open‖);

End if;

End;

Page 12: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

WINTER 2016

Q. Define cursor? List the two types of cursor. 2 Marks

Cursor: A cursor is a temporary work area created in the system memory when a SQL

statement is executed.

Types of Cursor: 1.Implicit Cursor 2.Explicit Cursor

Q. Explain the exception handling with its two type. 4 Marks

Exception Handling: Exception is nothing but an error. Exception can be raise when

DBMS encounters errors or it can be raised explicitly. When the system throws a

warning or has an error it can lead to an exception. Such exception needs to be handled

and can be defined internally or user defined. Exception handling is nothing but a code

block in memory that will attempt to resolve current error condition.

Syntax:

DECLARE

; Declaration section

…executable statement;

EXCEPTION

WHEN ex_name1 THEN

; Error handling statements/user defined action to be carried out;

END;

Types of Exception:

1) Predefined Exception/system defined exception/named exception:

Are always automatically raised whenever related error occurs. The most common

errors that can occur during the execution of PL/SQL. Not declared explicitly i.e.

cursor already open, invalid cursor, no data found, zero divide and too many rows

etc. Programs are handled by system defined Exceptions.

2) User defined exception:

It must be declare by the user in the declaration part of the block where the

exception is used.

It is raised explicitly in sequence of statements using:

Raise_application_error(Exception_Number,Error_Message);

Q. Explain Database security with its requirements. 4 Marks

Database Security: Database security refers to the collective measures used to protect

and secure a database or database management software from illegal use and malicious

Page 13: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

threats and attacks. Database security covers and enforces security on all aspects and

components of databases like Data stored in database, Database server, DBMS.

Data Security Requirements:

1. Authentication: System verifies a user's identity.

2. Authorization: Which database operations that user may perform (like read, update,

drop etc.) and which data objects that user may access.

3. Secure Storage of Sensitive Data: Once confidential data has been entered, its

integrity and privacy must be protected on the databases and servers wherein it

resides.

4. Integrity: Data integrate means that data is protected from deletion and corruption

5. Availability: A secure system makes data available to authorized users, without delay.

6. Confidentiality: A secure system ensures the confidentiality of data. This means

that it allows individuals to see only the data they are supposed to see.

Q. Explain PL/SQL Block structure. 4 Marks

Block structure of PL/SQL:

Declare

Declaration of memory variables

BEGIN (Mandatory)

SQL executable statements

Exception

Handling errors

END; (Mandatory)

A PL/SQL Block consists of following sections:

The Declaration section: Declaration of memory variables used later in begin section.

The Begin section: SQL executable statements for manipulating table data should be in

BEGIN..END block.

The Exception section: SQL and/or PL-SQL code to handle errors that may crop up

during execution of the above code block.

End : Mark the end of PL-SQL block

Q. What is database Trigger? How to create Trigger? 4 Marks

A trigger is a PL/SQL block structure which is fired when DML statements like Insert,

Delete, Update is executed on a database table. A trigger is triggered automatically when

an associated DML statement is executed.

Syntax for Creating a Trigger

CREATE OR REPLACE TRIGGER trigger_name

[BEFORE/AFTER]

Page 14: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

[INSERT/UPDATE/DELETE]

ON Table_name [FOR EACH STATEMENT/FOR EACH ROW]

[WHEN CONDITION]

PL/SQL block

Example:

CREATE OR REPLACE TRIGGER trg1

BEFORE INSERT ON EMP

FOR EACH ROW

BEGIN

IF :new.sal<=0 THEN

Rasie_application_error(„Salary should be greater than 0‟);

END IF;

END;

Q. Write a PL/SQL program to print even or odd number from given range (Accept

number range from user). 4 Marks

{**NOTE: any relevant program logic shall be considered**}

DECLARE

A NUMBER :=&A;

B NUMBER :=&B;

C NUMBER :=&C;

BEGIN

IF(C=1) THEN

FOR I IN A..B LOOP

IF(MOD(I,2)=0) THEN

DBMS_OUTPUT.PUT_LINE(I);

END IF;

END LOOP;

ELSE

FOR I IN A..B LOOP

IF(MOD(I,2)=1) THEN

DBMS_OUTPUT.PUT_LINE(I);

END IF;

END LOOP;

END IF;

END;

OR

Page 15: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

-- PL/SQL code to display even numbers

DECLARE

A NUMBER :=&A;

B NUMBER :=&B;

BEGIN

FOR I IN A..B LOOP

IF(MOD(I,2)=0) THEN

DBMS_OUTPUT.PUT_LINE(I);

END IF;

END LOOP;

END;

-- PL/SQL code to display odd numbers

DECLARE

A NUMBER :=&A;

B NUMBER :=&B;

BEGIN

FOR I IN A..B LOOP

IF(MOD(I,2)=1) THEN

DBMS_OUTPUT.PUT_LINE(I);

END IF;

END LOOP;

END;

Q. Explain function in PL/SQL with suitable example 4 Marks

A function (also called a user function or user-defined function) is a set of PL/SQL

statements that is called by name. A function returns a value to the environment in

which it is called.

Syntax:

CREATE [OR REPLACE] FUNCTION function_name [parameters]

RETURN return_datatype;

IS

Declaration_section

BEGIN

Execution_section

Return return_variable;

EXCEPTION

exception section

Return return_variable;

END;

Page 16: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Example :

CREATE OR REPLACE FUNCTION employer_details_func

RETURN VARCHAR(20);

IS

ename VARCHAR(20);

BEGIN

SELECT fname INTO ename

FROM emp WHERE empID = '100';

RETURN ename;

END;

Q. Explain two locking strategies. 4 Marks

Implicit Locking:

Oracle engine automatically locks table data while executing SQL statements

Explicit Locking:

The technique of lock taken on a table or its resources by a user is called Explicit

Locking. Users can lock tables they own or any tables on which they have been granted

table privileges (such as select, insert, update, delete). Explicit locking done by two

ways as

1) The Select........For Update statement

It is used for acquiring exclusive row level locks in anticipation of performing

updates on records.

2) Using lock table statement:

To manually override Oracle‟s default locking strategy by creating a data lock

in a specific mode.

Syntax:

LOCK TABLE <TableName> [, <TableName>]…

IN { ROW SHARE| ROW EXCLUSIVE|SHARE UPDATE|SHARE|SHARE

ROW EXCLUSIVE|EXCLUSIVE}

[NOWAIT]

Q. Explain loop control structure used in PL/SQL. 4 Marks

LOOP: PL/SQL LOOP statement is an iterative control statement that allows to execute

a sequence of statements repeatedly like WHILE and FOR loop.

Syntax:

LOOP

Page 17: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

sequence_of_statements;

END LOOP;

Example:

i number :=1;

Loop

dbms_out.put_line(„Good Morning‟);

i :=i+1;

Exit when i=10

End Loop

WHILE: If it is not known in advance how many times a sequence of statements needs

to execute. In such cases, one should use PL/SQL WHILE LOOP statement.

Syntax:

WHILE condition

LOOP

sequence_of_statements;

END LOOP;

Example:

i number := 1;

while (i<=10) Loop

dbms_output.put_line(i);

i :=i+1;

End Loop;

3) FOR: FOR loop is an iterative statement that execute a sequence of statements a

fixed number of times.

Syntax:

FOR loop_counter IN [REVERSE] lower_bound .. higher_bound

LOOP

sequence_of_statements;

END LOOP;

Example:

For i in 1..10 loop

dbms_output.put_line(i);

end loop;

Page 18: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

SUMMER-2015

Q. How to create trigger? State any two advantages of trigger.

(Trigger Syntax or example -2Marks, Any 2 advantages- 2 Marks)

[Note: Any relevant example can be considered]

The Syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

ON table_name

[FOR EACH ROW/For Each statement]

WHEN (condition)

BEGIN

--- sql statements

END;

(OR)

Example

CREATE or REPLACE TRIGGER After_Update_Row_product

AFTER

insert On product

FOR EACH ROW

BEGIN

INSERT INTO product_check Values('After update, Row level',sysdate);

END;

Advantages of triggers:

1. Triggers provide an alternative way to check the integrity of data.

2. Can catch errors in business logic in the database layer.

3. SQL triggers provide an alternative way to run scheduled tasks.

4. Triggers are very useful to audit the changes of data in tables.

Q. Write a PL/SQL program which handles divide by zero exception.

(Correct Program - 4 Marks)

DECLARE

A number:=20;

B number:=0;

C number;

BEGIN

dbms_output.put_line(„First Num : ‟||A);

dbms_output.put_line(„Second Num : ‟||B);

C:= A / B; --Raise Exception

Page 19: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

dbms_output.put_line(„ Result ‟ || C); -- Result will not be displayed

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line(„ Trying to Divide by zero :: Error ‟);

END;

/

Q. Draw the block structure of PL/SQL. List advantages of PL/SQL.

(Block structure – 2Marks, Any 4 advantages – 2 Marks)

Advantages of PL/SQL :

1. PL/SQL is that development tool which not only supports SQL data manipulations but

also provides facilities of conditional checking and looping.

2. PL/SQL sends an entire block of SQL statement to the ORACLE engine all in one go.

3. PL/SQL also permits dealing with errors as required, and facilitates displaying userfriendly

messages, when errors are encountered.

4. PL/SQL allows declaration and use of variables in blocks of code. These variables can be

used to store intermediate results of a query for later processing, or calculate values and

insert them into an ORACLE table later. PL/SQL variables can be used anywhere, either

in SQL statements or in PL/SQL blocks.

5. Applications written in PL/SQL are portable to any computer hardware and operating

system, where Oracle is operational.

Q. Explain Lock Compatibility Table. What is Two-phase locking protocol?

(Lock compatibility table – 2 Marks, two phase locking protocol – 2Marks)

The two commonly used locks are 1) shared and 2) Exclusive

1) Shared lock : It can lock the transaction only for reading.

2) Exclusive Lock : It can lock the transaction for reading as well as writing.

The compatibility table for these two locks can be given as:

Shared Exclusive

Shared Compatible Not compatible

Exclusive Not Compatible Not Compatible

Two phase locking protocol:

This protocol is for ensuring serializability.

Page 20: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

It requires the locking and unlocking of the transaction to be done in two phases.

1) Growing phase: In this phase, a transaction may obtain locks, but may not release

locks.

2) Shrinking phase: In this phase, a transaction may release locks, but may not acquire

any new locks.

Q. What are the various datatypes of PL/SQL?

(Any 4 data types -1Mark each)

The default data types that can be declared in Pl/SQL are :

1) number (size)– for storing numeric data

eg. a number(2);

2) char/ varchar(size) – for character data

eg: mynamevarchar(20);

3) date – for date and time data

eg : dob date;

4) Boolean – for storing true, false or null

eg: status Boolean;

5) %Type - to declare a variable or constant to have a same data type as that of a

previously defined variable or a column in a table.

e.g. enoemp.empno%type

Q. Write a PL/SQL program to create any snapshot.

(Creation of snapshot – 2 Marks, PL/SQL code – 2Marks)

[Note: Any other relevant example of PL/SQL code can be considered]

1) To create a snapshot :

Create snapshot emp_snap refresh with rowid as select * from emp;

2) To use snapshot from PL/SQL :

declare

cnt as number(2):=0;

begin

Select count(*) into cnt from emp_snap;

dbms_output.put_line („Number of rows from snapshot :‟ || cnt);

end;

/

Q. Write PL/SQL procedure to calculate factorial of a give number.

(Correct program – 4Marks)

[Note: Any other relevant logic shall be considered]

Page 21: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

SQL> create or replace procedure Factorial(n in number)

is

v number :=1;

begin

for i in 1..n

loop

v :=v * i;

end loop;

dbms_output.put_line(v);

end;

Procedure created

SQL> Begin

Factorial(5);

End;

Q. Differentiate between function and procedure.

(Any four point – 1Mark each)

Q. What are the various control structure statements used in PL/SQL?

(Any four control structures - 1 Mark each)

Conditional Control:

1. If then Else End If statement:

• The „If then Else End if is used to check the conditions.

• If the condition in if part is true then the statement in the if block gets execute.

• If the condition in if part is false then the statement given in the else part gets

execute.

• To give more number of conditions we can use „if the elseif‟ which provides more

Page 22: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

number of conditions.

• The general syntax of „if‟ is as follows:

If condition then

Statements

Else

Statements

End if;

2. Nested If:

• In this, any number of ELSIF clauses can be used with one IF statement.

• Either set of actions of the result of the first IF statement of ELSE statement can

contain further IF statements before specific actions are performed.

• Each nested IF statement must terminate with a corresponding END IF.

• Syntax:

If condition then

Statements

If condition then

Statements

Else

If condition then

Statements

Else condition then

Statements

End if;

End if;

End if;

3. Case

• Evaluates a list of conditions and returns one of multiple possible result

expressions.

• CASE can be used in any statement or clause that allows a valid expression. For

example, you can use CASE in statements such as SELECT, UPDATE, DELETE

and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and

HAVING.

• Synatx:

CASE [ expression ]

WHEN condition_1 THEN result_1

WHEN condition_2 THEN result_2

...

WHEN condition_n THEN result_n

Page 23: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

ELSE result

END

Iterative Control:

1. Simple Loop

2. While Loop

3. For Loop

1. Simple Loop

LOOP statements let you execute a sequence of statement multiple times.

Place the keyword LOOP before the first statement in the sequence and the

keyword END LOOP after the last statement in the sequence.

Syntax:

Endless loop

LOOP

<loop_body>

END LOOP;

Conditional loop

LOOP

<loop_body>

EXIT WHEN (Condition);

END LOOP;

The EXIT WHEN statement lets you complete a loop if further processing is impossible

or undesirable.

When the EXIT statement encountered, the condition in the WHEN clause is evaluated.

If the condition is true, the loop completes and control passes to the next statement.

2. While Loop

The WHILE LOOP statement associates a condition with a sequence of statements.

Before each iteration of loop, the condition is evaluated.

If the condition is true, the sequence of statement is executed, then control resumes at the

top of the loop.

If the condition is false or null, the loop is bypassed and control passes to the next

statement.

Syntax:

WHILE <Condition> LOOP

<loop body>

END LOOP;

3. For Loop :

Page 24: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

The FOR LOOP statement specifies a range of integers, then execute a sequence of

statements once for each integer in the range.

To reverse the range , “REVERSE” keyword is used.

The syntax is :

FOR i IN 1..N LOOP

<loop_body>

END LOOP;

4. Sequential Control:

Label can be used to give a label or name to the piece of code. And once the name is

given to it, user can call that piece of code with that label whenever and wherever

required in the program .

Syntax for label is as follows:

<<label_name>>

Statements;

The Goto statement is used to transfer the control or to change the sequence of the

instructions.

Syntax for goto statement is as follows:

Goto<<label_name>>

WINTER 2015

Q. What statement is used in PL/SQL to display the output?

(Correct statement – 2 Marks)

dbms_output.put_line( var/msg);

OR

set serveroutput on;

dbms_output.put_line( var/msg);

Q. What is Cursor?

(Cursor Description – 2 Marks)

Oracle creates a memory area, known as context area, for processing an SQL

statement, which

contains all information needed for processing the statement, for example, number of

rows processed, etc.

Q. What do you mean by database security?

(Database Security – 2 Marks; any relevant description shall be considered)

Database security refers to the collective measures used to protect and secure a

database or database management software from illegitimate use and malicious threats

and attacks.

Page 25: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Database security covers and enforces security on all aspects and components of

databases like Data stored in database, Database server, DBMS.

Q. Explain implicit and explicit locking strategy.

(Implicit Locking Strategy - 1 Mark; Explicit Locking Strategy - 3 Marks)

Implicit Locking:

Implicit locks are generally placed by the DBMS automatically.

Explicit Locking:

The technique of lock taken on a table or its resources by a user is called Explicit

Locking.

Users can lock tables they own or any tables on which they have been granted table

privileges

(such as select, insert, update, delete). Explicit locking done by two ways as

1) The Select........For Update statement

It is used for acquiring exclusive row level locks in anticipation of performing updates on

records.

2) Using lock table statement:

To manually override Oracle’s default locking strategy by creating a data lock in a

specific

mode.

Syntax:

LOCK TABLE <TableName> [, <TableName>]…

IN { ROW SHARE| ROW EXCLUSIVE|SHARE UPDATE|SHARE|SHARE ROW

EXCLUSIVE|EXCLUSIVE}

[NOWAIT]

Q. Write PL/SQL program to print even or odd numbers from given range. (Accept

number

from user.)

(Correct logic - 2 Marks, correct syntax – 2 Marks)

[** Note: Any relevant logic can be considered]

Logic 1 :

Declare

n1 number := &n1;

Page 26: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

n2 number :=&n2;

i number ;

begin

dbms_output.put_line(‘Even numbers are :’);

for i in n1..n2

loop

if mod(i,2)=0 then

dbms_output.put_line(i);

end if;

end loop;

dbms_output.put_line(‘Odd numbers are :’);

for i in n1..n2

loop

if mod(i,2)!=0 then

dbms_output.put_line(i);

end if;

end loop;

end;

Logic 2 :

Declare

n1 number := &n1;

n2 number :=&n2;

i number ;

begin

for i in n1..n2

loop

if mod(i,2)=0 then

dbms_output.put_line(‘Even :’ || i);

else

dbms_output.put_line(‘Odd :’ || i);

end if;

end loop;

end;

Q . Explain conditional control structure in PL/SQL.

(Explanation of each structure - 1 Mark, syntax of each - 1 Mark)

Conditional control statements in PL/SQL:

1. If then Else End if statement:

Page 27: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

PL/SQL provide ‘if’ statement to check conditions in program. If the given condition is

true, then the part after If statement gets executed, otherwise, part below else gets

executed.

Syntax:

If <condition> then

<action>

Else

<action>

End if;

2. Case

Evaluates a list of conditions and returns one of multiple possible result expressions.

CASE can be used in any statement or clause that allows a valid expression

Syntax:

CASE [ expression ]

WHEN condition_1 THEN result_1

WHEN condition_2 THEN result_2

...

WHEN condition_n THEN result_n

ELSE result

END CASE;

Q. What is lock based protocol? Explain share and exclusive mode protocols in lock based

protocol.

(Lock based protocol explanation – 2 Marks, shared and exclusive lock

explanation – 2 Marks)

Two phase locking protocol:

This protocol is for ensuring serializability.

It requires the locking and unlocking of the transaction to be done in two phases.

1) Growing phase: In this phase, a transaction may obtain locks, but may not

release locks.

2) Shrinking phase: In this phase, a transaction may release locks, but may not

acquire any new locks.

The two commonly used locks are 1) shared and 2) Exclusive

1) Shared lock: It can lock the transaction only for reading.

2) Exclusive Lock: It can lock the transaction for reading as well as writing.

1) The compatibility table for these two locks can be given as:

Page 28: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Q. What are adv.of PL/SQL? (Any four advantages – 1 Mark each)

Advantages of PL/SQL:

1. PL/SQL is that development tool which not only supports SQL data manipulations but

also

provides facilities of conditional checking and looping.

2. PL/SQL sends an entire block of SQL statement to the ORACLE engine all in one go.

3. PL/SQL also permits dealing with errors as required, and facilitates displaying user

friendly

messages, when errors are encountered.

4. PL/SQL allows declaration and use of variables in blocks of code. These variables

can be

used to store intermediate results of a query for later processing, or calculate values

and

insert them into an ORACLE table later. PL/SQL variables can be used anywhere,

either

in SQL statements or in PL/SQL blocks.

5. Applications written in PL/SQL are portable to any computer hardware and operating

system, where Oracle is operational.

Q. Write PL/SQL program to display factorial of any number.

(Correct logic – 2 Marks, correct syntax – 2 Marks)

[**Note: Any other relevant logic can be considered]

declare

f number :=1;

n number := &n;

begin

for i in 1..n

loop

f := f * i;

end loop;

dbms_output.put_line(f);

end;

/

Q. Explain implicit and explicit cursors.

(Implicit cursor – 2 Marks, Explicit cursor – 2 Marks)

Page 29: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Implicit Cursor:

Implicit cursors are automatically created by Oracle whenever an SQL statement is

executed, when

there is no explicit cursor for the statement.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit

cursor is

associated with this statement. For INSERT operations, the cursor holds the data that

needs to be

inserted. For UPDATE and DELETE operations, the cursor identifies the rows that

would be

affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which

always has the

attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The following

table

provides the description of the most used attributes

Explicit cursor:

Explicit cursors are programmer defined cursors for gaining more control over the

context area. An

explicit cursor should be defined in the declaration section of the PL/SQL Block. It is

created on a

SELECT Statement which returns more than one row.

Working with an explicit cursor involves four steps:

Declaring the cursor for initializing in the memory

Cursor cursor_name IS select_statement;

Opening the cursor for allocating memory

Open cursorname;

Fetching the cursor for retrieving data

Fetch cursorname INTO variable1,variable2…

Closing the cursor to release allocated memory

Close cursorname;

Q. Explain parameterized cursor with example.

(Explanation - 2 Marks, Any relevant Example - 2 Marks)

PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to

query.

PL/SQL Parameterized cursor define only datatype of parameter and not need to define

it's length.

Page 30: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

Default values is assigned to the Cursor parameters and scope of the parameters are

locally.

Parameterized cursors are also saying static cursors that can passed parameter value

when cursor

are opened.

Syntax to declare parameterized cursor:

CURSOR CursorName(VariableName Datatype)IS<SELECT statement…>

Opening A parameterized Cursor And Passing Values to the Cursor

OPEN CursorName(Value / Variable / Expression);

Example

Cursor display employee information from emp_information table whose emp_no is four

(4).

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;

/

Q. Give block structure of PL/SQL and explain main components.

(Block structure - 2 Marks, Explanation - 2 Marks)

Declare

Declaration of memory variables

BEGIN (Mandatory)

SQL executable statements

Exception

Handling errors

END; (Mandatory)

Page 31: RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND · PDF filesection to handle errors. End section marks the end of PLSQL block. Q. Explain locking strategy in detail. 4 Marks Implicit

A block begins with a declarative section where variables are declared. This is followed

by a section containing the procedural statements surrounded by BEGIN and END

keywords. Each block must have Begin and End statements and may optionally include

an exception section tohandle errors.