PL/SQL
Oracle
               Introduction
• PL/SQL is a block structured language that
  enables developers to combine the power of
  SQL with procedural statements.
• PL/SQL is an embedded language. PL/SQL only
  can execute in an Oracle Database. It was not
  designed to use as a standalone language like
  Java, C#, and C++. In other words, you cannot
  develop a PL/SQL program that runs on a
  system that does not have an Oracle Database.
       Structure of PL/SQL Block:
• PL/SQL have two types of Blocks
  – Anonymous blocks
  – Named blocks
  – Declare and exception
  sections are optional.
  – Typically, each block performs a logical action in the program
         Structure of PL/SQL Block:
• Declare section starts with DECLARE keyword in which variables,
  constants, records as cursors can be declared which stores data
  temporarily. It basically consists definition of PL/SQL identifiers. This
  part of the code is optional.
• Execution section starts with BEGIN and ends with END keyword. This is
  a mandatory section and here the program logic is written to perform
  any task like loops and conditional statements. It supports all DML
   commands, DDL commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is
  optional which contains statements that are executed when a run-time
  error occurs. Any exceptions can be handled in this section.
Basic structure of PL/SQL Program
                        First Program
SET SERVEROUTPUT ON;
BEGIN
   DBMS_OUTPUT.put_line ('Hello World!');
END;
/
• Output:
   Hello World!
   PL/SQL procedure successfully completed.
• Explanation:
  – SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
  – Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
  – PL/SQL procedure successfully completed.: It is displayed when the code is
    compiled and executed successfully.
                               First Program
• If you want to edit the code block, use the edit command. SQL*Plus will write the code block to
  a file and open it in a text editor as shown in the following picture:
• You can change the contents of the file like the following:
  begin
  dbms_output.put_line('Hello There');
  end;
  /
• And save and close the file. The contents of the file will be written to the buffer and
  recompiled.
• After that, you can execute the code block again, it will use the new code.
                      Second Program
• The next anonymous block example adds an exception-handling section which
  catches ZERO_DIVIDE exception raised in the executable section and displays an
  error message.
DECLARE
  v_result NUMBER;
BEGIN   
  v_result := 1 / 0;   
EXCEPTION       
  WHEN ZERO_DIVIDE THEN         
  DBMS_OUTPUT.PUT_LINE( ‘divisor cannot be zero’ );
  END;
/
 Output:
divisor cannot be zero
              PL/SQL identifiers
• PL/SQL identifiers are name given to constants,
  variables, exceptions, procedures, cursors, and
  reserved words. The identifiers consist of a letter
  optionally followed by more letters, numerals, dollar
  signs, underscores, and number signs and should
  not exceed 30 characters.
• By default, identifiers are not case-sensitive. So you
  can use integer or INTEGER to represent a numeric
  value. You cannot use a reserved keyword as an
  identifier.
          The PL/SQL Comments
• Program comments are explanatory statements that can
  be included in the PL/SQL code that you write and helps
  anyone reading its source code. All programming
  languages allow some form of comments.
• The PL/SQL supports single-line and multi-line comments.
  All characters available inside any comment are ignored
  by the PL/SQL compiler. The PL/SQL single-line comments
  start with the delimiter -- (double hyphen) and multi-line
  comments are enclosed by /* and */.
                  Variables
• Like several other programming languages,
  variables in PL/SQL must be declared prior to
  its use. They should have a valid name and
  data type as well.
• Syntax for declaration of variables:
  variable_name datatype [NOT NULL := value ];
                       Variables
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
   var1 INTEGER;
   var2 REAL;
   var3 varchar2(20) ;
BEGIN
   null;
END;
/
          INITIALISING and Displaying VARIABLES
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
   var1 INTEGER := 2 ;
   var2 varchar2(20) := 'I Love Programming' ;
BEGIN
    dbms_output.put_line(var1);
   dbms_output.put_line(var2);
END;
Output:
                 Taking input from user
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
  -- taking input for variable a
  a number := &a;
  -- taking input for variable b
  b varchar2(30) := &b;
BEGIN
  null;
END;
/
       PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
  -- taking input for variable a
  a integer := &a ;
  -- taking input for variable b
  b integer := &b ;
  c integer ;
BEGIN
  c := a + b ;
  dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
END;
/
             VALUE_ERROR Program
DECLARE
temp number;
BEGIN
temp:=‘Hello World’;
EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
dbms_output.put_line('Change data type of temp to varchar(20)');
END;
             User defined exceptions
DECLARE                                           EXCEPTION
x int:=&x; /*taking value at run time*/
y int:=&y;
                                                  WHEN exp1 THEN
div_r float;                                       dbms_output.put_line('Error');
exp1 EXCEPTION;                                    dbms_output.put_line('division by
exp2 EXCEPTION;                                    zero not allowed');
BEGIN
IF y=0 then
 raise exp1;                                      WHEN exp2 THEN
ELSEIF y > x then                                 dbms_output.put_line('Error');
 raise exp2;
ELSE
                                                  dbms_output.put_line('y is greater
 div_r:= x / y;                                   than x please check the input');
 dbms_output.put_line('the result is '||div_r);
END IF;
                                                  END;
User defined exceptions :Output
  PL/SQL Execution Environment
• The PL/SQL engine resides in the Oracle
  engine.The Oracle engine can process not only
  single SQL statement but also block of many
  statements. The call to Oracle engine needs to
  be made only once to execute any number of
  SQL statements if these SQL statements are
  bundled inside a PL/SQL block.
       PL/SQL Control Structures
• Testing Conditions:
  – IF and
  – CASE Statements
• Controlling Loop Iterations:
  – LOOP and
  – EXIT Statements
• Sequential Control:
  – GOTO and
  – NULL Statements
             IF and CASE Statements
• There are three forms of IF statements:
  – IF-THEN,
  – IF-THEN-ELSE, and 
  – IF-THEN-ELSIF
IF-THEN
IF-THEN-ELSE Statement
IF-THEN-ELSIF
NESTED-IF Statement
NESTED-IF Statement
Case Statements
          Equivalent IF THEN Ladder
Searched CASE Statement
               LOOP Statements
• Basic loop statement
• For loop statement
• While loop statement
• Use an EXIT statement to stop looping and prevent an
  infinite loop. 
Basic loop statement
          –There are two form
           of EXIT statements: 
             » EXIT and EXIT-WHEN.
            IF a> 5THEN
            EXIT;
            ENDIF;
            EXIT WHEN a> 5;
Nested loop and labeling of loops
For Loop
While Loop
Nesting of For and While Loop
              CONTINUE statement
• The CONTINUE statement causes the loop to skip one iteration of loop
  based on a condition.
                   GOTO statement
• A GOTO statement in PL/SQL programming language provides an
  unconditional jump from the GOTO to a labeled statement in the same
  subprogram.
Example of GOTO
Restrictions with GOTO Statement
         Using the NULL Statement
• The NULL statement does nothing and passes control to the next
  statement. Some languages refer to such instruction as a no-op (no
  operation).
               PL/SQL %TYPE Attribute
•   The %TYPE attribute allow you to declare a constant, variable, or parameter to be of the
   same data type as previously declared variable, record, nested table, or database
   column.
• Syntax:
    identifier Table.column_name%TYPE;
declare
     v_name employee.lastname%TYPE;
     v_dep  number;
     v_min_dep v_dep%TYPE:=31;
begin
     select lastname into v_name from EMPLOYEE where DEPARTMENTID=v_min_dep;
     DBMS_OUTPUT.PUT_LINE('v_name: '||v_name);
end;
DECLARE x NUMBER := 100;
BEGIN
EXECUTE IMMEDIATE 'create table my_table (n number)';
--Second, use DBMS_UTLIITY.EXEC_DDL_STATEMENT:
--DBMS_UTILITY.EXEC_DDL_STATEMENT ( 'create table my_table (n number)');
FOR i IN 1..10
 LOOP IF MOD(i,2) = 0 THEN
 -- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
 INSERT INTO temp VALUES (i, x, 'i is odd');
 END IF;
 x := x + 100;
END LOOP;
COMMIT;
END;