0% found this document useful (0 votes)
238 views

PLSQL Presentation

PL/SQL is a procedural language extension of SQL. It allows developers to logically group SQL statements, add control structures like conditionals and loops, and define reusable code in the form of procedures, functions and packages. Key features include scalar and composite data types, variables, control structures, interacting with databases using cursors, and exception handling.

Uploaded by

Sethu Lakshmi S
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
238 views

PLSQL Presentation

PL/SQL is a procedural language extension of SQL. It allows developers to logically group SQL statements, add control structures like conditionals and loops, and define reusable code in the form of procedures, functions and packages. Key features include scalar and composite data types, variables, control structures, interacting with databases using cursors, and exception handling.

Uploaded by

Sethu Lakshmi S
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

PL/SQL

Procedural Language/Structured Query Language

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

PL/SQL Character Set


Uppercase alphabets A-Z Lowercase alphabets a-z Digits 0-9 Symbols: ( ) + - * / < > = ! ; : . @ %,#$^&_\{ }?[]

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 .

Scalar Data Types


The scalar data types fall into one of four categories: number, character, Boolean, and date-time

Number Data Types


BINARY_INTEGER(-231 + 1 through 231 - 1 ) NATURAL (0 through 231 ) POSITIVE (1 through 231) NUMBER (1.0E-129 through 9.999E125 ) PLS_INTEGER (-2147483647 through 2147483647 ) Remaining are types of Number which are provided for maintaining compatibility with other DBMSs. DEC, DECIMAL , DOUBLE PRECISION, FLOAT, INT, INTEGER, NUMERIC, REAL, SMALLINT

Character Data Types


CHAR ( Fixed length character string up to 32767 characters long) VARCHAR2( Variable length character string up to 32767 characters
long)

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

Other Data Types


Boolean : BOOLEAN Date-time : DATE Large object (LOB) : BFILE BLOB CLOB

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.

How to declare variables ?


Declare a variable bonus that can hold 11 digits , two of which are after the decimal point. bonus number(11,2);

%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;

How to assign values to variables ?


Using the assignment operator := Eg: bonus:=basic*0.39;

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.

Conditional Control Statements


IF THEN END IF; This is the simplest form of the IF statement. The condition between the IF and THEN determines whether the set of statements between the THEN and END IF should be executed. If the condition evaluates to false, then the code is not executed.

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

The simple or infinite loop


The structure of the simple loop is the most basic of all the loop constructs. It consists of the LOOP keyword, the body of executable code, and the END LOOP keywords, as shown here: LOOP <executable statement(s)> END LOOP; The loop boundary consists solely of the LOOP and END LOOP reserved words. The body must consist of at least one

executable statement.
EXIT WHEN CAN BE USED TO EXIT FROM A SIMPLE LOOP

Numeric FOR loop


Here is the general syntax of the numeric FOR loop: FOR <loop index> IN [REVERSE] <lowest number> .. <highest number> LOOP <executable statement(s)> END LOOP; You must have at least one executable statement between the LOOP and END LOOP key words.

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.

The GOTO Statement


The GOTO statement performs unconditional branching to a named label. The general format for a GOTO statement is: GOTO label_name; where label_name is the name of a label. This GOTO label is defined in the program as follows: <<label_name>>

The NULL Statement


Usually when you write a statement in a program, you want it to do something. There are cases, however, when you want to tell PL/SQL to do absolutely nothing, and that is where the NULL statement comes in handy. The NULL statement has the following format: NULL;

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;

Interacting with Databases


From within PL/SQL, you can execute any DML (data manipulation language) statements, including INSERT, UPDATE, DELETE, and, SELECT When used without Cursors, a SELECT statement must return a single row only. Otherwise it will raise an error condition( Exception )

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=&regno; 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.

How to use Cursors


following cursor declaration associates the entire employee table with the cursor named employee_cur: CURSOR employee_cur IS SELECT * FROM employee; Once the cursor is declared, open it: OPEN employee_cur; And then fetch rows from it: FETCH employee_cur INTO employee_rec; and, finally, close the cursor: CLOSE employee_cur;

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;

Else dbms_output.put_line(unable to open cursor); End if; End;

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

Some of the System-defined exceptions


NO_DATA_FOUND : raised when a select statement returns zero rows TOO_MANY_ROWS: raised when select statement returns more than one row VALUE_ERROR: raised when there is a data type mismatch or if the variable size is smaller than required DUP_VAL_ON_INDEX: when an insert or update attempts to create two rows with duplicate values in columns constrained by unique index TIME_OUT_ON_RESOURCE: when a resource is not available with in the timeout limit

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;

How to use User-Defined Exceptions


Declare a user-defined exception in the declaration section of the PL/SQL block Use raise statement with in the program to throw this exception Handle this exception in the EXCEPTION block

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;

Modular Programing in PL/SQL


PL/SQL offers the following structures which modularize your code in different ways: Procedure A named PL/SQL block that performs one or more actions and is called as an executable PL/SQL statement. You can pass information into and out of a procedure through its parameter list. Function A named PL/SQL block that returns a single value and is used just like a PL/SQL expression. You can pass information into a function through its parameter list. Package A named collection of procedures, functions, types, and variables. A package is not really a module (it's more of a meta-module), but is so tightly related to modules.

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 ];

Use of Procedures : a SAMPLE PROGRAM

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.

Different Types of Records


Table-based A record based on a table's column structure.Each field corresponds to -and has the same name as -- a column in a table. Cursor-based A record based on the cursor's SELECT statement.Each field corresponds to a column or expression in the cursor SELECT statement. Programmer-defined A record whose structure the programmer, get to define with a declaration statement. Each field is defined explicitly (its name and datatype) in the TYPE statement for that record; a field in a programmer-defined record can even be another record.

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) );

Declaration of Record Variable prev_customer_sales_rec customer_sales_rectype; top_customer_rec customer_sales_rectype;

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

You might also like