Professional Documents
Culture Documents
OUTPUT Enter value for principal_amount: 100 old 15: p := &principal_amount; new 15: p := 100; Enter value for no_of_years: 3 old 17: n := &no_of_years; new 17: n := 3; Enter value for rate_of_interest: 9 old 19: r := &rate_of_interest; new 19: r := 9; simple interset =27 compound interset =129.5
If-else statements
OUTPUT Enter value for l: 3 old 13: l := &l; new 13: l := 3; Enter value for b: 5 old 15: b := &b; new 15: b := 5; the area iS < its perimeter area = 15 perimeter = 16
Loops
while loop
OUTPUT ENTER VALUE FOR N : 2545 THE SUM OF THE DIGITS = 16 PL/SQL PROCEDURE SUCESSFULLY COMPLETED.
* ** *** ****
DECLARE i number(1):=0; j number(1):=0; k number(1):=0; BEGIN for i in 0 .. 6 loop for j in 1 .. (6-i) loop dbms_output.put (' '); end loop; for k in i .. (3*i) loop dbms_output.put ('*'); end loop; dbms_output.put_line (' '); end loop; END; OUTPUT
* ** *** ****
Implicit Cursors:
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements. Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.
The status of the cursor for each of these attributes are defined in the below table. Attributes %FOUND Return Value Example The return value is TRUE, if the DML SQL%FOUND statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT .INTO statement return at least one row. The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT.INTO statement do not return a row. %NOTFOUND The return value is FALSE, if DML SQL%NOTFOUND statements like INSERT, DELETE and UPDATE at least one row and if SELECT .INTO statement return at least one row. The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT .INTO statement does not return a row. %ROWCOUNT Return the number of rows affected by the SQL%ROWCOUNT DML operations INSERT, DELETE, UPDATE, SELECT
Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor.
The General Syntax for creating a cursor is as given below: CURSOR cursor_name IS select_statement;
cursor_name A suitable name for the cursor. select_statement A select query which returns multiple rows.
DECLARE the cursor in the declaration section. OPEN the cursor in the Execution Section. FETCH the data from cursor into PL/SQL variables or records in the Execution Section.
CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
In the above example we are creating a cursor emp_cur on a query which returns the records of all the employees with salary greater than 5000. Here emp_tbl in the table which contains records of all the employees. 2) Accessing the records in the cursor: Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program.
How to access an Explicit Cursor? These are the three steps in accessing the cursor. 1) Open the cursor. 2) Fetch the records in the cursor one at a time. 3) Close the cursor. In the above PL/SQL Block, the salaries of all the employees in the employee table are updated. If none of the employees salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in employee table.
OUTPUT
Employee name is ALLEN Employee number is 7499 Employee job is SALESMAN Employee name is WARD Employee number is 7521 Employee job is SALESMAN Employee name is MARTIN Employee number is 7654 Employee job is SALESMAN Employee name is BLAKE Employee number is 7698 Employee job is MANAGER Employee name is TURNER Employee number is 7844 Employee job is SALESMAN Employee name is JAMES Employee number is 7900 Employee job is CLERK PL/SQL PROCEDURE SUCESSFULLY COMPLETED.
SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN BLAKE 2850 CLARK 2450 SCOTT 3000 KING TURNER ADAMS 1100 JAMES 950 FORD MILLER 1300 MILLER 1300
1250
Practical: Implementation of Subprograms, Functions and Procedures in PL|SQL and differences between Function and Procedure.
Subprograms are named PL/SQL blocks that can take parameters and be invoked.
PL/SQL has two types of subprograms called procedures and functions. Generally, you use a procedure to perform an action and a function to compute a value.
Like unnamed or anonymous PL/SQL blocks, subprograms have a declarative part, an executable part, and an optional exception-handling part. The declarative part contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These items are local and cease to exist when you exit the subprogram. The executable part contains statements that assign values, control execution, and manipulate Oracle data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution. CREATE [OR REPLACE] PROCEDURE procedure_name [{arguments} [{IN | OUT | IN OUT}] Argument type.] {IS | AS} PROCEDURE BODY;
Two types of procedures are Local procedure Stored procedure A procedure is called as a PL/SQL statement. A procedure can be called from any PL/SQL program by giving their names followed by parameters. Syntax is Procedure_name(arguments); Example to create a procedure to calculate the sum of series (1+2+3+4+ .n) CREATE OR REPLACE PROCEDURE Deepak(a in number) IS Tot number := 0; BEGIN FOR I IN 1 .. a LOOP Tot := tot + I; END LOOP; Dbms_output.put_line (the sum of series is || tot); END;
A procedure is a subprogram that performs a specific action. You write procedures using the syntax: [CREATE [OR REPLACE]] PROCEDURE procedure_name[(parameter[, parameter]...)] [AUTHID {DEFINER | CURRENT_USER}] {IS | AS} [PRAGMA AUTONOMOUS_TRANSACTION;] [local declarations] BEGIN executable statements [EXCEPTION exception handlers] END [name];
Advantages of Subprograms
Subprograms provide extensibility; that is, they let you tailor the PL/SQL language to suit your needs. For example, if you need a procedure that creates new departments, you can easily write one, as follows:
PROCEDURE create_dept (new_dname VARCHAR2, new_loc VARCHAR2) IS BEGIN INSERT INTO dept VALUES (deptno_seq.NEXTVAL, new_dname, new_loc); END create_dept;
Subprograms also provide modularity; that is, they let you break a program down into manageable, well-defined modules. This supports top-down design and the stepwise refinement approach to problem solving. In addition, subprograms promote reusability and maintainability. Once validated, a subprogram can be used with confidence in any number of applications. If its definition changes, only the subprogram is affected. This simplifies maintenance. Finally, subprograms aid abstraction, the mental process of deriving a universal from particulars. To use subprograms, you must know what they do, not how they work. Therefore, you can design applications from the top down without worrying about implementation details. Dummy subprograms (stubs) allow you to defer the definition of procedures and functions until you test and debug the main program.
OUTPUT Exec fact(5); Factorial : 120 Exec fact(10); Factorial : 3628800 PL/SQL PROCEDURE SUCESSFULLY COMPLETED.
/* PROGRAM TO CREATE A PROCEDURE TO PERFORM ADD, SUBTRACT, MULTIPY AND DIVISION OF TWO NUMBERS */ DECLARE a number; b number; c number; d number; e number; f number; Procedure menu (a in number, b in number, c out number, d out number, e out number, f out number) IS BEGIN c:=a+b; d:=a-b; e:=a*b; f:=a/b; END; BEGIN a:=&a; b:=&b; menu(a,b,c,d,e,f); dbms_output.put_line('Addition'|| c); dbms_output.put_line('Subtraction'||d ); dbms_output.put_line('Multiplication'|| e ); dbms_output.put_line('Division'|| f ); END; OUTPUT Enter value for a :Enter value for b :Addition 10 Subtraction 6 Multiplication 16 Division 4 PL/SQL PROCEDURE SUCESSFULLY COMPLETED. 8 2
FUNCTION
Function is a type of subprogram that can accept parameters, perform an action and return the values to the calling PL/SQL block. Functions can be called by blocks, other function & procedures. A function must have a return clause. A function is a subprogram that
computes a value. Functions and procedures are structured alike, except that functions have a RETURN clause. A function can be called in the calling block in the following way is
Variable:=function_name (function variables); Syntax to create a function is CREATE [OR REPLACE] FUNCTION function_name [{arguments} [{IN | OUT | IN OUT}] RETURN return_type.] {IS | AS} FUNCTION BODY; RETURN expression; Example to create a function to calculate area of circle CREATE OR REPLACE FUNCTION Deepak(pi number:=3.14) RETURN number IS area number; rad number; BEGIN rad := 3; While rad <= 7 LOOP area := pi * power (rad,2); rad := rad + 1; RETURN area; END LOOP; END; Actual parameters : List of variables or expressions referenced in the parameter list of a subprogram call is called as actual parameters. Formal parameters : List of variables declared in the subprogram specified and Referenced in the subprogram body is called as actual parameters.
FUNCTION
A function is subprogram that accepts parameters, compute a Value & return that value to the caller. It returns only one value. It returns value as direct output We use function to compute a value.
A package is a collection of PL/SQL elements that are "packaged" or grouped together within a special BEGIN-END syntax, a kind of "meta-block." Here is a partial list of the kinds of elements you can place in a package:
Cursors Variables (scalars, records, tables, etc.) and constants Exception names and pragmas for associating an error number with an exception PL/SQL table and record TYPE statements Procedures and functions
Packages are among the least understood and most underutilized features of PL/SQL. That's a shame because the package structure is also one of the most useful constructs for building well-designed PL/SQL-based applications. Packages provide a structure to organize your modules and other PL/SQL elements. They encourage proper structured programming techniques in an environment that often befuddles the implementation of structured programming. When you place a program unit into a package you automatically create a
"context" for that program. By collecting related PL/SQL elements in a package, you express that relationship in the very structure of the code itself. Packages are often called "the poor man's objects" because they support some, but not all, object-oriented rules. The PL/SQL package is a deceptively simple, yet powerful construct. It consists of up to two distinct parts: the specification and the body.
The package specification, which defines the public interface (API) of the package: those elements that can be referenced outside of the package. The package body, which contains the implementation of the package and elements of the package you want to keep hidden from view.
Figure 2 shows how these different types of packages interact as layers of PL/SQL code and packages that are available to you. We describe the types further in "Types of Packages" later in this chapter.
You can declare variables and include headers of both cursors and modules (and only the specifications). You must have at least one declaration or header statement in the package specification.
Syntax of Triggers
/* PROGRAM TO CREATE A TRIGGER FOR EMP TABLE WHICH MAKES ENTRY IN ENAME COLUMN IN UPPERCASE */
create or replace trigger Deepak before insert or update of ename on emp for each row BEGIN :new.ename:=upper(:new.ename); dbms_output.put_line(:new.ename); END; OUTPUT TRIGGER CREATED PL/SQL PROCEDURE SUCESSFULLY COMPLETED.
/* PROGRAM TO CREATE A TRIGGER ON THE EMP TABLE WHICH SHOW THE OLD AS WELL AS NEW VALUE OF THE EMPLOYEE NAME AFTER ANY UPDATION ON ENAME */
create or replace trigger t2 after update or delete of ename on emp for each row BEGIN dbms_output.put_line('old name:|| : old.dname'); dbms_output.put_line('new name:|| : new.dname'); END;
OUTPUT SQL> set serveroutput on SQL> ed function SQL> @ xyz.txt 8 / Trigger created. SQL> update emp set ename ='marks' where empno=7900 2 / old name:|| : old.dname new name:|| : new.dname 1 row updated.