PLSQL Presentation
PLSQL Presentation
SQL is the language used to communicate with an RDBMS. But it does not have any procedural capabilities such as looping and branching.
PL/SQL is an extension of SQL. It bridges the gap between database technology and procedural programming languages. It allows to use all the SQL data manipulation statements as well as procedural techniques such as looping and branching. It allows to logically group a number of SQL statements and treat them as a single block
Variables
Can be up to 30 characters in length Must start with a letter Can then be composed of any of the following: letters, numerals, $, #, and _
Data Types
PL/SQL has scalar and composite data types. A scalar data type is an atomic; it is not made up of other variable components. A composite data type has components. The two composite types currently supported by PL/SQL are the record and table .
VARCHAR (
same as VARCHAR2)
LONG (can store variable-length strings of up to 32760 bytes RAW ( to store binary data up to 32767 bytes) LONG RAW (to store binary data up to 32760 bytes) ROWID (to store rowids from the database
PL/SQL Comments
Single line comment: The comment line begins with a --. The entire line will be treated as comment. Multi line comment: Begins with a /* and ends with a */. This type of comment can span multiple lines of code.
%TYPE declares a variable or constant to have the same data type as that of a previously defined variable or of a column in a table or a view. Eg: name1 student.name%type;
Declaration continues
The keyword CONSTANT can be used to declare a constant. For example da CONSTANT number(3,2):=0.39; The clause NOT NULL can be used to declare a variable which must hold a value always. Eg: x number(2) NOT NULL:=5;
Structure of a PL/SQL PROGRAM( BLOCK) DECLARE Declaration of variables and other objects BEGIN Executable statements EXCEPTIONS Exception handling statements END;
Write a program to find the sum of two variables Declare A integer; B integer; C integer; Begin A:=3; B:=4; C:=A+B; dbms_output.put_line(Sum=||c); End;
Nesting of blocks and scope of variables Each program block in PL/SQL can contain other blocks. ie blocks can be nested. A variable declared in outer block is available in inner block also. If a variable declared in outer block is again declared in inner block, inner variable will have priority over the outer variable.
IF THEN ELSE END IF; This combination implements an either/or logic: based on the condition between the IF and THEN keywords, either execute the code between the THEN and ELSE or between the ELSE and END IF. One of these two sections of executable statements is performed.
IF
THEN
ELSIF THEN ELSE END IF; This last and most complex form of the IF statement selects an action from a series of mutually exclusive conditions and then executes the set of statements associated with that condition.
Write a program to accept rollno, name, marks and date of birth and calculate grade according to the following condition. Marks>=90 grade=A Marks>=70 and <90 grade=B Marks>=60 and <70 grade=C Marks>=40 and <60 grade=D Else failed. declare roll integer; name varchar2(10); mark float; date_birth date; grade varchar2(5); begin roll:=:roll; name:=:name;
mark:=:mark; date_birth:=:date_birth; if mark>=90 then grade:=A; elsif mark>=70 then grade:=B; elsif mark>=60 then grade:=C; elsif mark>=40 then grade=D; else grade=F; end if; dbms_output.put_line(Name :||name); dbms_output.put_line(Grade :||grade); dbms_output.put_line(Marks :||mark); end;
LOOPS
PL/SQL provides three different kinds of loop constructs: The simple or infinite loop The FOR loop (numeric and cursor) The WHILE loop
executable statement.
EXIT WHEN CAN BE USED TO EXIT FROM A SIMPLE LOOP
Here is the general syntax for the WHILE loop: WHILE <condition> LOOP <executable statement(s)> END LOOP; where <condition> is a Boolean variable or an expression that evaluates to a Boolean value of TRUE, FALSE, or NULL. Each time an iteration of the loop's body is to be executed, the condition is checked. If it evaluates to TRUE, then the body is executed. If it evaluates to FALSE or to NULL, then the loop terminates and control passes to the next executable statement following the END LOOP statement.
Write a program to print the fibanocci series up to n\ Declare f integer:=1; s integer:=1; l integer; Begin dbms_output.put_line(f); dbms_output.put_line(s); l:=f+s; while l<=20 loop dbms_output.put_line(l); f:=s; s:=l; l:=f+s; End loop; End;
A table student contains regno, name and total marks. Write a program to print the details of a student if regno is given. (structure regno, name and marks). Declare r student.regno%type; n student.name%type; m student.mark%type; Begin select regno, name, mark into r,n,m from student where regno=®no; dbms_output.put_line(r || n || m); End;
Qn. A table student contains the regno, name and total marks. Write a program to print the grade of a student according to the following condition. If mark>=90 Mark<90 and mark>=75 Mark<75 and mark>=60 Mark<60 and mark>=50 Mark<50 and mark>=40 If mark<40 grade=A grade=B grade=C grade=D grade=E grade=F
Qn. A table named EMPLOYEE contains empno, name and basic. Write a program to update the salary of a particular employee with salary 12000.
Declare n employee.empno%type; na employee.name%type; b employee.basic%type; Begin select empno, name, basic into n,na,b from employee where empno=&empno; dbms_output.put_line(n || ||na|| ||b); update employee set basic=12000 where empno=n; select empno, name, basic into n,na,b from employee where empno=n; dbms_output.put_line(n || || na || ||b); End;
Cursor
When you execute a SQL statement from PL/SQL, the Oracle RDBMS assigns a private work area for that statement. This work area contains information about the SQL statement and the set of data returned or affected by that statement. The PL/SQL cursor is a mechanism by which you can name that work area and manipulate the information within the area.
Cursor attributes
%NOTFOUND: is true if a fetch could not retrieve data t from he cursor %FOUND: opposite of the above %ROWCOUNT: returns the number of rows that have been fetched so far %ISOPEN: is true if the curson is open
USE OF CURSORS: A SAMPLE PROGRAM DECLARE name1 EMP.name%type; desig1 EMP.desig%type; cursor c1 is select name,desig from EMP; begin open c1; loop fetch c1 into name1,desig1; exit when c1%notfound; dbms_output.put_line(name1||' , ' ||desig1); end loop; Close c1; end;
Write a PL/SQL block to delete records of student in std 9 from student table. Declare cursor mycursor is select regno, std from student for update; b mycuror%rowtype; Begin open mycursor; loop fetch mycursor into b; exit when mycursor%notfound; if b.std=9 then delete form student where current of mycursor; end if; end loop; Close mycursor; End;
Raise the salary of a particular employee by 0.15 after accepting empno and update the salary, display the message whether record found or not.
Begin update employee set salary=salary+salary*0.15 where emp_code=&emp_code; If SQL%FOUND then dbms_output.put_line(Record modified); Else dbms_output.put_line(employee not found); End if; End;
SQL%ROWCOUNT Declare row_affected number(4); Begin update employee set salary=salary+salary*0.15 where job=Programmer; Rows_affected:=sql%rowcount; If sql%rowcount>0 then dbms_output.put_line(rows_affected||record modified successfully); Else dbms_output.put_line(No programmers); End if; End;
Write a PL/SQL block to update the salary of each employee in a particular department and insert a record in the emp_raise table. Accept deptno and increase the salary by 0.05 and insert it into emp_raise table. Emp_raise table should contain emp_code, date on which the salary is changed and incresed salary. Declare cursor c_emp is select emp_code , salary from employee where dept=Acc ; ecode employee.emp_code%type; n_sal employee.salary%type; Begin open c_emp; If c_emp%isopen then Loop fetch c_emp into e_code,n_sal; exit when c_emp%NOTFOUND; update employee set salary=salary+n_sal*0.05 where mp_code=&emp_code; insert into emp_raise values(ecode,sysdate, n_sal*0.05); End loop; Close c_emp;
Exceptions
Exceptions are pre-defined error conditions. Exceptions can be either system-defined or user-defined When an Exception occurs, it can be handled in the Exception block of PL/SQL program
Exception handling: A sample program DECLARE name1 student.name%type; id1 student.name%type; begin id1:=&ID; select name into name1 from student where id=id1; dbms_output.put_line(name1); exception when no_data_found then dbms_output.put_line('Sorry, No matching records found'); end;
User Defined Exception: A sample program DECLARE a number(2); b number(2); c NUMBER(3); deno_zero exception; begin a:=:a; b:=:b; if b=0 then raise deno_zero; end if; c:=a/b; dbms_output.put_line('Result='||c); exception when deno_zero then dbms_output.put_line('Division by Zero not allowed'); end;
Procedures A procedure is a module performing one or more action. The general format of a PL/SQL procedure is as follows: PROCEDURE name [ ( parameter [, parameter ... ] ) ] IS [declaration statements] BEGIN executable-statements [ EXCEPTION exception handler statements] END [ name ];
Create PROCEDURE SUM1(a in number, b in number) is c number; begin c:=a+b; dbms-output.put_line(c); end; The above procedure can be called from a main program as follows Declare a number; b number; Begin a:=&a; b:=&b; sum1 (a,b); End;
Functions A function is a module that returns a value. Unlike a procedure, which is a standalone executable statement, a call to a function can only be part of an executable statement. Because a function returns a value, it can be said to have a datatype. A function can be used in place of an expression in a PL/SQL statement having the same datatype as the function.
Structure of a Function The structure of a function is the same as that of a procedure, except that the function also has a RETURN clause. The general format of a function follows: FUNCTION name [ ( parameter [, parameter ... ] ) ] RETURN return_datatype IS [ declaration statements ] BEGIN executable statements [ EXCEPTION exception handler statements ] END [ name ];
create or replace FUNCTION add1 (a integer, b integer) return integer is s integer; begin s:=a+b; Return s; end; Main program declare a1 integer; b1 integer; s1 integer; begin a1:=:a1; b1:=:b1; s1:=add1(a1,b1); dbms_output.put_line(s1); end;
Writing PL/SQL Procedures/Functions PL/SQL functions returns a scalar value and PL/SQL procedures return nothing. Both can take zero or more number of parameters as input or output. The special feature about PL/SQL is that a procedure/function argument can be of input (indicating the argument is read-only), output (indicating the argument is write-only) or both (both readable and writable). For example, the following is a PL/SQL procedure and a function. PROCEDURE hire_employee (emp_id INTEGER, name VARCHAR2) IS BEGIN INSERT INTO employee VALUES (emp_id, name, 1000); END hire_employee; FUNCTION sal_ok (salary REAL, title REAL) RETURN BOOLEAN IS min_sal REAL; max_sal REAL; BEGIN SELECT losal, hisal INTO min_sal, max_sal FROM sals WHERE job = title; RETURN (salary >= min_sal) AND (salary <= max_sal); END sal_ok; A function is called as part of an expression. For example, the function sal_ok might be called as follows: IF sal_ok(new_sal, new_title) THEN ...
Package
A package is a collection of PL/SQL objects 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 objects you can place in a package: Cursors Variables (scalars, records, tables, etc.) Constants Exception names PL/SQL table and record TYPE statements Procedures Functions
The Specification The package specification contains the definition or specification of all elements in the package that may be referenced outside of the package Package <name> is <declarations such as procedure, function > end <name>;
The Body The body of the package contains all the code behind the package specification: the implementation of the modules, cursors, and other objects
Records in PL/SQL A record is a composite data structure, which means that it is composed of more than one element or component, each with its own value. The record as a whole does not have value of its own; instead, each individual component or field has a value. The record gives you a way to store and access these values as a group.
Declaring Programmer-Defined Record TYPEs You declare a record type with the record TYPE statement. The TYPE statement specifies the name of the new record structure, and the components or fields which make up that record. The general syntax of the record TYPE definition is: TYPE <type_name> IS RECORD (<field_name1> <datatype1>, <field_name2> <datatype2>, ... <field_nameN> <datatypeN> );where <field_nameN> is the name of the Nth field in the record and <datatypeN> is the datatype of that Nth field. The datatype of a record's field can be any of the following: Pre-defined datatype (VARCHAR2, NUMBER, etc.) Programmer-defined subtype (PL/SQL Release 2.1 and above) Declarations using %TYPE attributes Declarations using %ROWTYPE attributes PL/SQL record type PL/SQL table type
Type Declaration TYPE customer_sales_rectype IS RECORD (customer_id NUMBER (5), customer_name customer.name%TYPE, total_sales NUMBER (15,2) );
PL/SQL TABLES
A PL/SQL table is a one-dimensional, unbounded, sparse collection of homogeneous elements, indexed by integers. Like PL/SQL records, PL/SQL tables are composite data structures
Defining the Table TYPE The TYPE statement for a PL/SQL table has the following format: TYPE <table_type_name> IS TABLE OF <datatype> [ NOT NULL ] INDEX BY BINARY_INTEGER;where <table_type_name> is the name of the table structure you are creating and <datatype> is the datatype of the single column in the table. You can optionally specify that the table be NOT NULL, meaning that every row in the table that has been created must have a value. You must always specify INDEX BY BINARY_INTEGER at the end of the TYPE...TABLE statement, even though it is the only type of index you can have currently in a PL/SQL table.
Declaring the PL/SQL Table Once you have created your table type, you can reference that table type to declare the actual table. The general format for a table declaration is: <table_name> <table_type>; where <table_name> is the name of the table and <table_type> is the name of a previously declared table type