0% found this document useful (0 votes)
90 views25 pages

What Is PL/SQL?: PL/SQL Stands For Procedural Language Extension of SQL

PL/SQL is a programming language developed by Oracle Corporation to enhance the capabilities of SQL. A PL/SQL block consists of three sections: declaration, execution, and exception handling. It allows procedural and object-oriented programming capabilities. PL/SQL code can be stored and executed on both client-side and server-side. It offers advantages like block structure, procedural language capabilities, better performance, and error handling.

Uploaded by

Ran Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
90 views25 pages

What Is PL/SQL?: PL/SQL Stands For Procedural Language Extension of SQL

PL/SQL is a programming language developed by Oracle Corporation to enhance the capabilities of SQL. A PL/SQL block consists of three sections: declaration, execution, and exception handling. It allows procedural and object-oriented programming capabilities. PL/SQL code can be stored and executed on both client-side and server-side. It offers advantages like block structure, procedural language capabilities, better performance, and error handling.

Uploaded by

Ran Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

What is PL/SQL?

PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90s to enhance the capabilities of SQL.

A Simple PL/SQL Block:


Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block. A PL/SQL Block consists of three sections:

The Declaration section (optional). The Execution section (mandatory). The Exception (or Error) Handling section (optional).

Declaration Section: The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and Records, which stores data temporarily. Cursors are also declared in this section. Execution Section: The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section and is the section where the program logic is written to perform any task. The programmatic constructs like loops, conditional statement and SQL statements form the part of execution section. Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors. Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be used to document code. This is how a sample PL/SQL Block looks.

DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END;

The PL/SQL Engine: Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in the client system (client-side) or in the database (server-side).

Advantages of PL/SQL:

Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused.

Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops).

Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic.

Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.

PL/SQL Variables
These are placeholders that store the values that can change through the PL/SQL Block. The General Syntax to declare a variable is:
variable_name datatype [NOT NULL := value ];

variable_name is the name of the variable. datatype is a valid PL/SQL datatype. NOT NULL is an optional specification on the variable. value or DEFAULT valueis also an optional specification, where you can initialize a variable. Each variable declaration is a separate statement and must be terminated by a semicolon.

For example, if you want to store the current salary of an employee, you can use a variable.
DECLARE salary number (6); -- salary is a variable of datatype number and of length 6. When a variable is specified as NOT NULL, you must initialize the variable when it is declared. For example: The below example declares two variables, one of which is a not null. DECLARE salary number(4); dept varchar2(10) NOT NULL := HR Dept;

The value of a variable can change in the execution or exception section of the PL/SQL Block. We can assign values to variables in the two ways given below. 1) We can directly assign values to variables. The General Syntax is:
variable_name:= value;

2) We can assign values to variables directly from the database columns by using a SELECT.. INTO statement. The General Syntax is:
SELECT column_name INTO variable_name FROM table_name [WHERE condition];

Attributes

PL/SQL variables and cursors have attributes, which are properties that let you reference the datatype and structure of an item without repeating its definition. Database columns and tables have similar attributes, which you can use to ease maintenance. A percent sign (%) serves as the attribute indicator.
%TYPE

The %TYPE attribute provides the datatype of a variable or database column. This is particularly useful when declaring variables that will hold database values. For example, assume there is a column named title in a table named books. To declare a variable named my_title that has the same datatype as column title, use dot notation and the %TYPE attribute, as follows:
my_title books.title%TYPE;

Declaring my_title with %TYPE has two advantages. First, you need not know the exact datatype of title. Second, if you change the database definition of title (make it a longer character string for example), the datatype of my_title changes accordingly at run time.
%ROWTYPE

In PL/SQL, records are used to group data. A record consists of a number of related fields in which data values can be stored. The %ROWTYPE attribute provides a record type that represents a row in a table. The record can store an entire row of data selected from the table or fetched from a cursor or cursor variable. Columns in a row and corresponding fields in a record have the same names and datatypes. In the example below, you declare a record named dept_rec. Its fields have the same names and datatypes as the columns in the dept table.
DECLARE dept_rec dept%ROWTYPE; -- declare record variable

Example: The below program will get the salary of an employee with id '1116' and display it on the screen.
DECLARE var_salary number(6); var_emp_id number(6) := 7902; emp_name varchar(20); BEGIN SELECT ename,sal FROM emp WHERE empno = var_emp_id; dbms_output.put_line('Emp id: '||var_emp_id); dbms_output.put_line(' dbms_output.put_line(' END; / Name : '||emp_name); ' || var_salary); INTO emp_name,var_salary

salary :

NOTE: The backward slash '/' in the above program indicates to execute the above PL/SQL Block.

Conditional Statements in PL/SQL


As the name implies, PL/SQL supports programming language features like conditional statements, iterative statements. The programming constructs are similar to how you use in programming languages like Java and C++. In this section I will provide you syntax of how to use conditional statements in PL/SQL programming. IF THEN ELSE STATEMENT
1) IF condition THEN statement 1; ELSE

statement 2; END IF; 2) IF condition 1 THEN statement 1; statement 2; ELSIF condtion2 THEN statement 3; ELSE statement 4; END IF 3) IF condition1 THEN ELSE IF condition2 THEN statement1; END IF; ELSIF condition3 THEN statement2; END IF;

Example:
declare n1 number; n2 number; n3 number; begin n1:=&n1; n2:=&n2; n3:=&n3; if n1>n2 and n1>n3 then dbms_output.put_line('Big number = '||n1);

elsif n2>n3 then dbms_output.put_line('Big number = '||n2); else dbms_output.put_line('Big number = '||n3); end if; end;

Case Statement:
The syntax for the case statement is: CASE [ expression ] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... WHEN condition_n THEN result_n ELSE result END expression is optional. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n) condition_1 to condition_n must all be the same datatype. Conditions are evaluated in the order listed. Once a condition is found to be true, the case statement will return the result and not evaluate the conditions any further. Example:

DECLARE n_salary EMP.SAL%TYPE; n_emp_id EMP.EMPno%TYPE := 7900; v_msg VARCHAR(20);

BEGIN SELECT sal INTO n_salary FROM emp WHERE empno = n_emp_id; CASE WHEN n_salary < 2000 THEN v_msg := 'Low'; WHEN n_salary >= 2000 AND n_salary <=3000 THEN v_msg := 'Fair'; WHEN n_salary >= 3000 THEN v_msg := 'High'; END CASE; DBMS_OUTPUT.PUT_LINE(v_msg); END; /

Iterative Statements in PL/SQL:


An iterative control Statements are used when we want to repeat the execution of one or more statements for specified number of times. These are similar to those in

There are three types of loops in PL/SQL: Simple Loop While Loop For Loop
1) Simple Loop

A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT condition is satisfied the process exits from the loop.
The General Syntax to write a Simple Loop is:
LOOP statements; EXIT; {or EXIT WHEN condition;} END LOOP;

These are the important steps to be followed while using Simple Loop.

1) Initialise a variable before the loop body. 2) Increment the variable in the loop. 3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition, the statements in the loop is executed only once.
2) While Loop

A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
The General Syntax to write a WHILE LOOP is:
WHILE <condition> LOOP statements; END LOOP;

Important steps to follow when executing a while loop:

1) Initialise a variable before the loop body. 2) Increment the variable in the loop.

3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.
3) FOR Loop

A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter reachs the value of the end integer. The General Syntax to write a FOR LOOP is:
FOR counter IN val1..val2 LOOP statements; END LOOP;

val1 - Start integer value. val2 - End integer value.

Important steps to follow when executing a while loop:

1) The counter variable is implicitly declared in the declaration section, so it's not necessary to declare it explicity. 2) The counter variable is incremented by 1 and does not need to be incremented explicitly. 3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done oftenly.

Examples: Loop: declare n number:=1; begin loop dbms_output.put_line(n); n:=n+1; exit when n>10;

end loop; end; / While: declare n number:=&n; f number:=1; i number:=2; begin while(i<=n) loop f:=f*i; i:=i+1; end loop; dbms_output.put_line('Factorial = '||f); end; /

For Loop: declare tableno number:=&tno; begin for i in 1..10 loop dbms_output.put_line(tableno||' * '||i||' = '|| tableno*i); end loop; end; /

Stored Procedures
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists of declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

A procedure may or may not return any value. General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END;

IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section. The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code.

We can pass parameters to procedures in three ways. 1) IN-parameters 2) OUT-parameters 3) IN OUT-parameters A procedure may or may not return any value. The below example creates a procedure employer_details which gives the details of the employee.

create procedure GetEmpDetails(eno number) as name varchar(20); esal number; begin select ename,sal into name,esal from emp where empno=eno; dbms_output.put_line('Emp Id : '||eno); dbms_output.put_line('Name : '||name); dbms_output.put_line('Salary : '||esal); end; /
How to execute a Stored Procedure?

There are two ways to execute a procedure. 1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;

2) Within another procedure simply use the procedure name.

procedure_name;

Example: create procedure GetNetSalary(eno in number,incentives in number,netsal out number) as name varchar(20); esal number; begin select ename,sal into name,esal from emp where empno=eno; netsal:=esal+incentives; dbms_output.put_line('Emp Id : '||eno); dbms_output.put_line('Name : '||name); dbms_output.put_line('Salary : '||esal); dbms_output.put_line('Net Salary : '||netsal); end; /

PL/SQL Functions
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value. The General Syntax to create a function is:
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;

1) Return Type: The header section defines the return type of the function. The return datatype can be any of the oracle datatype like varchar, number etc. 2) The execution and exception section both should return a value which is of the datatype defined in the header section. For example, lets create a frunction called ''employer_details_func' similar to the one created in stored proc

create function SumOfSalaries return number as tsal number; begin select sum(sal) into tsal from emp; return tsal; end;

/
How to execute a PL/SQL Function?

A function can be executed in the following ways. 1) Since a function returns a value we can assign it to a variable.
employee_name := employer_details_func;

If employee_name is of datatype varchar we can store the name of the employee by assigning the return type of the function to it. 2) As a part of a SELECT statement
SELECT employer_details_func FROM dual;

3) In a PL/SQL Statements like,


dbms_output.put_line(employer_details_func);

This line displays the value returned by the function.

Exception Handling
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly. When an exception occurs a messages which explains its cause is recieved. PL/SQL Exception message consists of three parts. 1) Type of Exception 2) An Error Code 3) A message By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.
2) Structure of Exception Handling.

The General Syntax for coding the exception section


DECLARE Declaration section BEGIN Exception section EXCEPTION WHEN ex_name1 THEN

-Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements END;

General PL/SQL statments can be used in the Exception Block. When an exception is raised, Oracle searches for an appropriate exception handler in the exception section. For example in the above example, if the error raised is 'ex_name1 ', then the error is handled according to the statements under it. Since, it is not possible to determine all the possible runtime errors during testing fo the code, the 'WHEN Others' exception is used to manage the exceptions that are not explicitly handled. Only one exception can be raised in a Block and the control does not return to the Execution Section after the error is handled. If there are nested PL/SQL blocks like this.
DELCARE Declaration section BEGIN DECLARE Declaration section BEGIN Execution section EXCEPTION Exception section END; EXCEPTION Exception section END;

In the above case, if the exception is raised in the inner block it should be handled in the exception block of the inner PL/SQL block else the control moves to the Exception block of the next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly with an error.
3) Types of Exception.

There are 3 types of Exceptions. a) Named System Exceptions b) User-defined Exceptions


a) Named System Exceptions

System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions.

For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions. Named system exceptions are: 1) Not Declared explicitly, 2) Raised implicitly when a predefined Oracle error occurs, 3) caught by referencing the standard name within an exception-handling routine.
Exception Name Reason Error Number

CURSOR_ALREADY_OPEN When you open a cursor that is already open. INVALID_CURSOR

NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE

ORA06511 When you perform an invalid operation on a cursor ORAlike closing a cursor, fetch data from a cursor that is 01001 not opened. When a SELECT...INTO clause does not return any ORArow from a table. 01403 When you SELECT or fetch more than one row into ORAa record or variable. 01422 When you attempt to divide a number by zero. ORA01476

For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below.
BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END;

Example:

declare eno number:=&eno; name varchar(20); esal number; begin select name,sal into name,esal

from emp where empno=eno; dbms_output.put_line('Name : '||name); dbms_output.put_line('salary : '||esal); exception when no_data_found then dbms_output.put_line(' Employee not found '); end;

User-defined Exceptions

Apart from sytem exceptions we can explicity define exceptions based on business rules. These are known as user-defined exceptions. Steps to be followed to use user-defined exceptions: They should be explicitly declared in the declaration section. They should be explicitly raised in the Execution Section. They should be handled by referencing the user-defined exception name in the exception section. For Example: Lets consider the product table and order_items table from sql joins to explain user-defined exception. Lets create a business rule that if the total no of units of any particular product sold is more than 20, then it is a huge quantity and a special discount should be provided.
DECLARE e_invalid_product EXCEPTION; BEGIN update emp SET sal=4500 WHERE empno = &enoumber;

IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT; DBMS_OUTPUT.PUT_LINE ('salary updated'); EXCEPTION WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE ('INVALID emp NO'); END; /

What are Cursors?


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. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. There are two types of cursors in PL/SQL:
Implicit cursors:

These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed.
Explicit cursors:

They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

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

Return Value

Example

%FOUND

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 statements SQL%NOTFOUND 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

We've categorized cursors into the following topics: Declare a Cursor OPEN Statement FETCH Statement CLOSE Statement

For Example: CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;

Example: write a Pl/sql block to display all employees whose sal >1500.

declare cursor c1 is select empno,ename,sal from emp where sal>=1500; eno number; empname varchar(20); esal number;

begin open c1; loop fetch c1 into eno,empname,esal; exit when c1%notfound; if esal>=1500 then dbms_output.put_line(eno||' '||empname||' end if; end loop; close c1; end; / Cursor Using For Loop: declare cursor c1 is select empno,ename,sal from emp where sal>=1500; begin for rec in c1 loop if rec.sal>=1500 then dbms_output.put_line(rec.empno||' '||rec.sal); end if; end loop; end;

'||esal);

'||rec.ename||'

Trigger
A trigger is a pl/sql block structure which is fired when a 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 of Triggers The Syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER {BEFORE | AFTER | INSTEAD OF {INSERT [OR] | UPDATE [OR] | [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS [FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END; trigger_name } DELETE} n]

Example: to print a message when a row inserted. create or replace trigger tr1 after INSERT on tab1 begin dbms_output.put_line('New row Inserted...'); end; / Example: to store the deleted of tab1 into tab2 CREATE OR REPLACE TRIGGER d_tab1 AFTER DELETE ON tab1 FOR EACH ROW declare eno number; begin eno:= :old.id; insert into tab2(eid) values(eno); end; /

Example: to check the values when updating the data CREATE OR REPLACE TRIGGER updateTab1 before UPDATE on tab1 for each row begin if(:new.id< :old.id) then RAISE_APPLICATION_ERROR(-20001, ' new value should not be less than old value'); end if; end;

You might also like