PL/SQL Basics
   Recognize the basic PL/SQL block and its sections.
   Describe the significance of variables in PL/SQL.
   Declare PL/SQL variables.
   Execute a PL/SQL block.
                          PL/SQL Basics
 PL/SQL is a combination of SQL along with the procedural features of programming
  languages.
 It was developed by Oracle Corporation in the early 90's to enhance the capabilities
  of SQL.
 PL/SQL is one of three key programming languages embedded in the Oracle
    Database, along with SQL itself and Java.
   PL/SQL is a completely portable, high-performance transaction-processing language.
   PL/SQL provides a built-in, interpreted and OS independent programming
    environment.
   PL/SQL can also directly be called from the command-line SQL*Plus interface.
   Direct call can also be made from external programming language calls to database.
   PL/SQL's general syntax is based on that of ADA and Pascal programming language
                Features of PL/SQL
 PL/SQL has the following features
 PL/SQL is tightly integrated with SQL.
 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.
 It supports object-oriented programming.
 It supports the development of web applications and server pages.
                     Advantages of PL/SQL
 SQL is the standard database language and PL/SQL is strongly
  integrated with SQL.
 PL/SQL supports both static and dynamic SQL.
   Static SQL supports DML operations and transaction control
    from PL/SQL block.
   In Dynamic SQL, SQL allows embedding DDL statements in
    PL/SQL blocks.
                               Con…
 PL/SQL allows sending an entire block of statements to the database at one
  time. This reduces network traffic and provides high performance for the
  applications.
 PL/SQL saves time on design and debugging by strong features, such as
  exception handling, encapsulation, data hiding, and object-oriented data
  types.
 Applications written in PL/SQL are fully portable.
 PL/SQL provides support for Object-Oriented Programming.
                PL/SQL - Basic Syntax
 PL/SQL programs are divided and written in logical blocks of code.
 Each block consists of three sub-parts
1.    Declarations
      This section starts with the keyword DECLARE. It is an optional section
       and defines all variables, cursors, subprograms, and other elements to be
       used in the program.
                          Con…
2. Executable Commands
 This section is enclosed between the keywords BEGIN and
  END and it is a mandatory section.
 It consists of the executable PL/SQL statements of the program.
 It should have at least one executable line of code, which may
  be just a NULL command to indicate that nothing should be
  executed.
Exception Handling
 This section starts with the keyword EXCEPTION. This
   optional section contains exception(s) that handle errors in the
   program.
         DECLARE
         <declarations section>
         BEGIN
         <executable command(s)>
         EXCEPTION
         <exception handling>
         END;
                    Example
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
          The PL/SQL Identifiers
 PL/SQL identifiers are 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.
         The PL/SQL 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 */.
                                  Con…
    DECLARE
    -- variable declaration
    message varchar2(20):= 'Hello, World!';
    BEGIN
    /*
    * PL/SQL executable statement(s)
    */
    dbms_output.put_line(message);
    END;
    /
 When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.
           PL/SQL Program Units
 A PL/SQL unit is any one of the following
     PL/SQL block
     Function
     Package
     Package body
     Procedure
     Trigger
     Type
     Type body
               Types of Variables
a) Scalar – this data types hold a single value. (data types that
corresponds with column types.
b) Composite – they allow groups of fields to be defined and
manipulated in blocks.
c) References – they hold values, called pointers, but designate
other program items.
          PL/SQL Programming
set serveroutput on
Declare
a integer;
b integer;
c integer;
f real;
Begin
a:=&a;
b:=&b;
c:=a+b;
f:=a/b;
dbms_output.put_line('a+b = '||c);
dbms_output.put_line('a/b = '||f);
end;
/
create table circle(
radius number(5,2),
diameter number(5,2),
circum number(5,2),
area number(5,2)
);
declare
pi constant number:=3.14;
rad circle.radius%type:=4.5;
dia circle.diameter%type;
cirm circle.circum%type;
area circle.area%type;
begin
dia := 2* rad;
cirm:=2.0*pi*rad;
area:=pi*rad**2;
insert into circle values(rad, dia, cirm, area);
end;
/
           Variable Scope in PL/SQL
 Local variables - variables declared in an inner block and not
  accessible to outer blocks.
  Global variables - variables declared in the outermost block or
  a package.
              PL/SQL - CONDITIONS
 IF-THEN Statement
 IF condition THEN
 S;
 END IF;
 IF-THEN-ELSE Statement
  IF condition THEN
     S1;
   ELSE
     S2;
  END IF;
                                      Con…
IF-THEN-ELSIF Statement
 IF(boolean_expression 1)THEN
 S1; -- Executes when the Boolean expression1 istrue
 ELSIF( boolean_expression 2) THEN
 S2; --Executes when the Boolean expression 2 is true
 ELSIF( boolean_expression 3) THEN
 S3;--Executes when the Boolean expression 3 istrue
 ELSE
 S4; -- executes when the none of the above condition is true
 END IF;
Example
create table emp(
eno integer,
ename varchar(12),
ebdate date,
esalary number(9,2)
);
insert into emp values(1,'Dawit','12-sep-1990',4500);
insert into emp values(2,'Beti','22-Jan-1990',6500);
insert into emp values(3,'Chala','21-feb-1990',7500);
insert into emp values(4,'Sara','19-jul-1990',8500);
insert into emp values(5,'Dani','16-apr-1990',9500);
declare
id emp.eno%type:=&id;
name emp.ename%type;
sal emp.esalary%type;
begin
select eno, ename, esalary into id,name,sal from emp where eno=id;
if(sal<6000) then
dbms_output.put_line('Employee '||name||' earns the min salry of '||sal);
end if;
end;
/
CASE Statement
Example
Searched CASE Statement
PL/SQL — Loops
 PL/SQL provides the following types of loop to handle the
  looping requirements.
   Basic loop
   For loop
   While Loop
Basic Loop Statement
WHILE LOOP Statement
FOR LOOP Statement
Syntax
   FOR counter IN initial_value .. final_value LOOP
    sequence_of_statements;
       END LOOP;
 Example
 DECLARE
   a
 number(2);
 BEGIN
      FOR a
    in 10 ..
    20 LOOP
       dbms_output.put_line('value
   of a: ' || a); END LOOP;
     END;
Reverse FOR LOOP Statement
The Loop Control Statements
Example
 DECLARE
 a number(2) :=10;
 BEGIN
 -- while loop execution
 WHILE a < 20 LOOP
 dbms_output.put_line ('value of a: ' || a);
 a := a + 1;
 IF a > 15 THEN
 -- terminate the loop using the exit statement
 EXIT;
 END IF;
     END LOOP;
 END;
 /
Continue statement
 Example
 DECLARE
    a number(2) := 10;
 BEGIN
        -- while loop execution
    WHILE a < 20 LOOP
           dbms_output.put_line ('value of a: ' || a);
           a := a + 1;
           IF a = 15 THEN
              -- skip the loop using the CONTINUE statement a
           := a + 1;
           CONTINUE
        ; END IF;
        END LOOP;
    END;
    /
Goto statement
  DECLARE
  a number(2) := 10; BEGIN
  <<loopstart>>
  -- while loop execution
  WHILE a < 20 LOOP
  dbms_output.put_line ('value of a:
  ' || a);
  a := a + 1;
  IF a = 15 THEN
  a := a + 1;
  GOTO loopstart;
  END IF;
  END LOOP;
  END;
  /
              SQL Methods
 Procedure
 Function
                                Triggers
 Triggers are stored programs, which are automatically executed or fired when
  some events occur.
 Triggers are, in fact, written to be executed in response to any of the following
  events:
 A database manipulation DML statement DELETE, INSERT, or UPDATE.
 A database definition DDL statement CREATE, ALTER, or DROP.
 A database operation SERVERERROR, LOGON, LOGOFF, STARTUP, or
  SHUTDOWN.
 Triggers could be defined on the table, view, schema, or database with which
  the event is associated.
                 Creating Triggers
 The syntax for creating a trigger is:
                   EXCEPTIONS
 An error condition during a program execution is called an
  exception in PL/SQL.
 There are two types of exceptions:
   System-defined exceptions
   User-defined exceptions
  
Syntax
       User-defined Exceptions
 PL/SQL allows you to define your own exceptions
 according to the need of your program.
 A user defined exception must be declared and then
 raised explicitly, using
 RAISE statement or
 The procedure
 DBMS_STANDARD.RAISE_APPLICATION_ERROR.
 The syntax for declaring an exception is:
 DECLARE
  my-exception EXCEPTION;
                                                 EXCEPTION
DECLARE
c_id customers.id%type := &cc_id;                 WHEN ex_invalid_id THEN
c_name customers.name%type;                       dbms_output.put_line('ID must be greater
c_addr customers.address%type;
-- user defined exception                         than zero!');
ex_invalid_id EXCEPTION;                          WHEN no_data_found THEN
BEGIN
IF c_id <= 0 THEN                                 dbms_output.put_line('No such
RAISE ex_invalid_id;                              customer!');
ELSE
SELECT name, address INTO c_name, c_addr          WHEN others THEN
FROM customers                                    dbms_output.put_line('Error!');
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);         END;
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);     /
END IF;