Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Aim:

1. Write and execute PL-SQL Cursor programs.


2. Write and execute PL-SQL Functions and Procedure programs.

Prerequisite: SQL Server, SQL, Programming Language concepts.

Outcome: Create programs to execute on XML and relational database systems


Theory:

Whenever you issue a SQL Statement, Oracle opens an area of memory in which the command is parsed
and executed. This Area is called CONTEXT AREA.
 The information (Rows) retrieved from the database table, which is available in context area, is known
as the ACTIVE SET.
 A Cursor is a pointer to the current row in the ACTIVE SET.
 There are two types of Cursors:
1. Implicit Cursors: Created, Managed & Erased by Oracle Automatically.
2. Explicit Cursors: Created & Named by the Programmer.

Controlling Explicit Cursor:

Steps Involved in Creating a Cursor:


1. Create the context area

Syntax: Cursor <cursor_name> is <SQL Query>.


2. Opening the CURSOR

Syntax: OPEN <cursor_name>;


3. Fetch the record into a cursor variable.

Syntax: FETCH <cursor name> into <cursor variable>;


4. CLOSE the cursor.

Syntax: CLOSE <cursor name>;


Cursor Attributes:
 <cursor name> %isopen

 <cursor name> %found

 <cursor name> %notfound

 <cursor name> %rowcount

Function is a named PL/SQL Block that returns a value.


 A Function can be stored in the database as a schema object for repeated execution.
 A function is called as part of an expression.
 Functions and Procedures are structured alike. Procedures are used to perform a task and Functions
are used to compute values.
Location to call User-Defined Functions:
 Select Command.
 Where, Group by, Having & Order by Clauses.
 In an Insert Statement.
 In Update Statement.
Restrictions On Functions:
 Functions Called from a SQL Statements cannot have DML statements.
 Functions called from an update / delete statement on a table XYZ cannot perform DML on the same
table XYZ.
 Functions called from a DML statement on a table cannot query the same table.
 Functions called from a SQL statement cannot contain COMMIT or ROLLBACK statement.
Procedures:
 A Procedure is a named PL/SQL Block, stored in the database.
 A Procedure is generally used to perform an action.
 A Procedure may or may not return a value.
 When a procedure is first created, it is compiled and stored with in the database in compiled form.
This compiled code allows reusability and performance benefits.
 Parameter can have three modes in a procedure, IN, OUT & INOUT mode.

Privileges:
SQL> grant create procedure to user_name; (DBA)
SQL> Grant Execute on <procedure_name> to user_name (owner)
Data Dictionary Views:
 User_procedures ( General Info )
 User_source ( the text of pl/sql procedure)
 Desc procedure_name ( IN, OUT, INOUT parameters list)
 User_errors (to see all the compilation errors in a procedure).

OR
SQL> show error;
Show err;

Practice Exercise:
1. Using implicit cursor update the salary by an increase of 10% for all the records in
EMPLOYEES table, and finally display how many records have been updated. If no
records exist display the message None of the salaries were updated.
2. WAP to accept the employee_id and display all the details of employees.If employee
doesnot exist display the appreciate message
3. Using explicit cursor fetch the employee name, employee_id and salary of all the
records from EMPLOYEES table.
4. Using explicit cursor Insert the records from EMPLOYEES table for the columns
employee_id, Last_Name and salary for those records whose salary exceeds 2500 into a
new table TEMP_EMP.
5. Write a Program to add a record in Department table using Procedure
6. Write a Program to fetch data from Emp table using Procedure.
7. Demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the reverse of a number.
8. Write a PL SQL program to demonstrate function with IN and OUT Parameters.

Instructions:
1. Write and execute the programs in Oracle SQL server.
2. Paste the snapshot of the output in input & output section.

Code and Output:

1. Using implicit cursor update the salary by an increase of 10% for all the records in
EMPLOYEES table, and finally display how many records have been updated. If
no records exist display the message None of the salaries were updated.

DECLARE
z_empid emp.empno%TYPE;
z_empname emp.ename%TYPE;
z_salary emp.sal%TYPE;
CURSOR employee_cursor IS -- declaring a cursor
SELECT empno,
ename,
sal
FROM emp;

BEGIN
OPEN employee_cursor; -- opening the cursor
LOOP
FETCH employee_cursor -- fetching records from the cursor
INTO z_empid,
z_empname,
z_salary;
EXIT
WHEN employee_cursor%NOTFOUND;
IF (z_salary < 8000) THEN
z_salary:=z_salary*1.1;
dbms_output.Put_line(z_empid
|| ' '
|| z_empname
|| ' '
|| z_salary);
ELSE
dbms_output.Put_line('no record exixst');
END IF;
END LOOP;
CLOSE employee_cursor; --closing the cursor
END;
/

2. WAP to accept the employee_id and display all the details of employees. If
employee does not exist display the appreciate message
DECLARE
z_emp emp%rowtype;
eid number;
BEGIN
eid:=:eid;
select *
into z_emp
from emp
where empno = eid;

if(eid =z_emp.empno)then
dbms_output.Put_line(z_emp.empno
|| ' '
|| z_emp.ename
|| ' '
|| z_emp.sal);
else
dbms_output.Put_line('Employee with this ID does not exist');
end if;
end;
/

3. Using explicit cursor fetch the employee name, employee_id and salary of all the
records from EMPLOYEES table.
DECLARE
z_empid emp.empno%TYPE;
z_empname emp.ename%TYPE;
z_salary emp.sal%TYPE;
CURSOR employee_cursor IS -- declaring a cursor
SELECT empno,
ename,
sal
FROM emp;

BEGIN
OPEN employee_cursor; -- opening the cursor
LOOP
FETCH employee_cursor -- fetching records from the cursor
INTO z_empid,
z_empname,
z_salary;
EXIT

WHEN employee_cursor%NOTFOUND;

dbms_output.Put_line(z_empid
|| ' '
|| z_empname
|| ' '
|| z_salary);
END LOOP;
CLOSE employee_cursor; --closing the cursor
END;
/

4. Using explicit cursor Insert the records from EMPLOYEES table for the columns
employee_id, Last_Name and salary for those records whose salary exceeds 2500
into a new table TEMP_EMP.
DROP TABLE temp_emp;
CREATE TABLE temp_emp AS
SELECT empno,ename,sal
FROM emp;
DELETE FROM temp_emp;
COMMIT;

DECLARE
z_empid emp.empno%TYPE;
z_empname emp.ename%TYPE;
z_salary emp.sal%TYPE;

CURSOR cur_st IS
SELECT empno,
ename,
sal
FROM emp
WHERE sal > "2500";
BEGIN
OPEN cur_st;
LOOP
FETCH cur_st INTO z_empid,z_empname, z_salary;
EXIT WHEN cur_st%NOTFOUND;
INSERT INTO temp_emp
(empno,
ename,
sal)
VALUES (z_empid,
z_empname,
z_salary);

END LOOP;
CLOSE cur_st;
COMMIT;
END;
/

5. Write a Program to add a record in Department table using Procedure

CREATE OR REPLACE PROCEDURE insert_department (


p_depno dept.deptno%TYPE,
p_name dept.dname%TYPE,
p_location dept.loc%TYPE)
IS
BEGIN
INSERT INTO dept (deptno,dname,loc)
VALUES (p_depno, p_name, p_location);
COMMIT;
END;
/
6. Write a Program to fetch data from Emp table using Procedure.

PROCEDURE get_emp_names (dept_num IN NUMBER) IS


emp_name VARCHAR2(10);
CURSOR c1 (depno NUMBER) IS
SELECT ename FROM emp
WHERE deptno = depno;
BEGIN
OPEN c1(dept_num);
LOOP
FETCH c1 INTO emp_name;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_name);
END LOOP;
CLOSE c1;
END;

7. Demonstrate Declaring, Defining and Invoking a simple PL/SQL


function which will compute and return the reverse of a number.

set serveroutput on;


declare
   
    a int;
    c int;
    n int;
   rev int:=0;
    r int;
  
// Defining function 
function reverse_it( x  IN int) 
return  int
as
z int;
  
// function code
begin
    n := x;
          
    while (n > 0)
    loop
        r := mod(n, 10);
        rev := (rev * 10) + r;
        n := trunc(n / 10);
    end loop;
      
    z := rev;
    return z;
      
end  ;  

BEGIN  
   a := 123456789;    
     
   c := reverse_it(a);  
   dbms_output.put_line('the reverse of number is  ' || c);  
  
END;  

Output:
the reverse of number is 987654321

8. Write a PL SQL program to demonstrate function with IN and OUT Parameters.


DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/

Output:

Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.

Observation & Learning:


We got to learn the concepts of cursor programs and functional procedure programs.
Conclusion:
We successfully executed the programs.
Questions:
1. Differentiate Implicit and Explicit Cursor.
The main difference between the implicit cursor and explicit cursor is that an explicit cursor
needs to be defined explicitly by providing a name while implicit cursors are automatically
created when you issue a select statement. Furthermore, multiple rows can be fetched using
explicit cursors while implicit cursors can only fetch a single row. Also NO_DATA_FOUND
and TOO_MANY_ROWS exceptions are not raised when using explicit cursors, as opposed to
implicit cursors. In essence, implicit cursors are more vulnerable to data errors and provide less
programmatic control than explicit cursors. Also, implicit cursors are considered less efficient
than explicit cursors.

2. State the Advantages and Applications of Cursor.


Advantages of using Cursor: 
 Using Cursor we can perform row by row processing so we can perform row wise
validation or operations on each row.
 Cursors can provide the first few rows before the whole result set is assembled. Without
using cursors, the entire result set must be delivered before any rows are displayed by the
application. So using cursor, better response time is achieved. 
 If we make updates to our without using cursors in your application then we must send
separate SQL statements to the database server to apply the changes. This can cause the
possibility of concurrency problems if the result set has changed since it was queried by the
client. In turn, this raises the possibility of lost updates. So using cursor, better concurrency
Control can be achieved.
 Cursors can be faster than a while loop but at the cost of more overhead.
Application:
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed by
it. This temporary work area is used to store the data retrieved from the database, and
manipulate this data.

3. Differentiate Procedure and Functions with examples.


Example of procedure:

CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

Example of function:

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/

You might also like