SlideShare una empresa de Scribd logo
1 de 12
Descargar para leer sin conexión
Chap 1. Introduction To PL/SQL         1



                        1. Introduction To PL/SQL

1.   What is PL/SQL? What are the disadvantages of SQL?
     PL/SQL stands for Procedural Language extension to SQL. PL/SQL is a 3GL which extends
     SQL by adding programming capabilities, such as programming structures and subroutines,
     similar to those available in high-level languages. Thus, PL/SQL is a super set of SQL.

     PL/SQL is a block-structured language i.e., each bock can perform one logical unit of a job.
     PL/SQL is used for server-side and client-side development. PL/SQL is also used to develop
     applications for browsers.

     SQL is a natural language for database management system but some of the drawbacks of
     SQL are as follows:
     1. SQL does not have the capabilities of programming languages such as looping, branching,
        checking for conditions, etc. These capabilities are important before data storage.
     2. SQL does not have error-handling capabilities. While processing or executing a SQL
        statement if an error occurs, Oracle displays its own error messages.
     3. SQL statements are passed to the Oracle engine, one at a time. Every time a statement is
        executed, a call is made to the engine’s resources. This decreases the data processing speed
        as repeated calls must be made to the network.

2.   What are the advantages of PL/SQL?
     PL/SQL is used in most Oracle products. The advantages of PL/SQL are as follows:
     1. Development tool: PL/SQL is a development tool. It supports SQL data management.
     2. OOPs: PL/SQL has support for object-oriented programs and this provides the advantages
         of data encapsulation or data hiding.
     3. Better Performance: When a PL/SQL block is processed then the entire block is sent to the
         server and not just individual statements. So if a PL/SQL block contains many SQL
         statements, then it is treated as one call to the server. If PL/SQL is not used then each SQL
         statement will result in a separate call to the database server.
     4. Improved error handling: PL/SQL permits user-friendly error messages to be displayed
         instead of the standard cryptic Oracle error messages.
     5. Variables can be declared and used in blocks of code. These variables can be used to store
         intermediate values of calculations or query processing and used later. Calculation can be
         done and stored in Oracle tables.
     6. Portability: Applications developed in PL/SQL are portable across any platform –
         hardware and software, including operating systems.
     7. Higher Productivity: Users can do procedural programming.
     8. Integration with Oracle: PL/SQL supports all SQL datatypes.
     9. Support for developing web applications and pages.
     10. Access to pre-defined packages.


 3   Explain the generic 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 Declare section (optional): The Declaration section of a PL/SQL Block starts with the


mukeshtekwani@hotmail.com                                                 Prof. Mukesh N. Tekwani
2    Chap 1. Introduction To PL/SQL


              reserved keyword DECLARE. This section is optional and is used to declare any variables,
              constants, records and cursors, which are used to manipulate data in the execution section.
         •    The Begin or Execution section: This section begins with the keyword BEGIN and ends
              with the keyword END. It consists of a set of SQL and PL/SQL statements which describe
              processes that have to be applied to the table data. This section contains statements for data
              manipulation, looping, branching and data retrieval.
         •    The Exception (or Error) Handling section (optional) – 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.
         •    A typical code block looks like this:

                     DECLARE
                          Declaration of Variables, constants, cursors, etc
                     BEGIN
                          SQL executable statements and PL/SQL executable statements
                     EXCEPTION
                          SQL block to handle errors that may arise due to execution of
                          code in the BEGIN block.
                     END;
                     /

         Note the / sign at the end of the code. This tells Oracle to run the block. If the procedure is
         completed successfully, Oracle generates the following message: “PL/SQL procedure
         completed successfully”.

     4   Explain the PL/SQL Execution environment / PL/SQL architecture
         • The PL/SQL engine is a part of the Oracle engine. The Oracle engine can process
            individual SQL statements and also PL/SQL blocks.
         • Blocks of code are sent to the PL/SQL engine where the procedural statements are
            executed and the SQL statements are sent to the SQL executor in Oracle engine.
         • When a number of SQL statements are combined into a PL/SQL block, the call to the
            Oracle engine is made only once. This process is illustrated below:

             PL/SQL block of code                                                Oracle Engine
             DECLARE
                  Procedural statements;                                         PL/SQL Engine
             BEGIN
                  Procedural Statements;
                  SQL statements;
             EXCEPTIONS                                                      SQL statement Executor
                  SQL statements;
             END

         The PL/SQL compilation and run-time system is an engine that compiles and executes
         PL/SQL blocks and subprograms. The engine can be installed in an Oracle server or in an

    Prof. Mukesh N Tekwani                                                mukeshtekwani@hotmail.com
Chap 1. Introduction To PL/SQL          3


     application development tool such as Oracle Forms.

     The PL/SQL engine executes procedural statements but sends SQL statements to the SQL
     engine in the Oracle database. This is shown in the following figure:




 5   Write a note on PL/SQL Character Set.
     Character set of PL/SQL is as follows:
     upper- and lower-case letters A .. Z and a .. z
     numerals 0 .. 9
     symbols ( ) + - * / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ] tabs, spaces, and carriage returns

     Lexical units: Words used in PL/SQL are called lexical units. Blank spaces have no effect on
     the PL/SQL block.
     E.g.,
     IF x > y THEN
             max := x;
     ELSE
             max := y;
     END IF;

     Compound symbols used in PL/SQL are >= <= != || >> << := **
     Literals: It is a numeric value or a character string.
     Numeric Literal: These can be either integer or float. E.g., 35, 3.142
     Character literal: It consists of a single character enclosed between single quotes sign. E.g.
     ‘A’.
     String Literal: These are characters stored in single quotes. E.g., ‘Mumbai’. If a single quote
     character must itself be a part of the string literal, than it must appear twice, e.g., ‘Mumbai’’s
     weather is good’.
     Logical (Boolean) literal: These are predetermined constants with values of TRUE, FALSE
     or NULL.

     Comments
     The PL/SQL compiler ignores comments, but we should put comments to improve code
     readability and maintenance. PL/SQL supports two comment styles: single-line and multi-line.
     Single-Line Comments: Single-line comments begin with a double hyphen (--) anywhere on
     a line and extend to the end of the line. A few examples are:

mukeshtekwani@hotmail.com                                                      Prof. Mukesh N. Tekwani
4    Chap 1. Introduction To PL/SQL


         -- begin processing
         SELECT sal INTO salary FROM emp -- get current salary
           WHERE empno = emp_id;
         bonus := salary * 0.15; -- compute bonus amount

         Comments can appear within a statement at the end of a line.

         While testing or debugging a program, you might want to disable a line of code. The following
         example shows how you can "comment-out" the line:
         -- DELETE FROM emp WHERE comm IS NULL;

         Multi-line Comments
         Multi-line comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can
         span multiple lines. This is similar to C or Java style. Examples are:
         BEGIN
           ...
           /* Compute a 15% bonus for top-rated employees. */
           IF rating > 90 THEN
               bonus := salary * 0.15   /* bonus is based on salary */
           ELSE
               bonus := 0;
           END IF;
           ...
         /* The following line computes the area of a circle using pi, which is the ratio between
         the circumference and diameter. */
         area := pi * radius**2;
         END;

     6   Write a note on PL/SQL data types.
         Every constant, variable, and parameter has a datatype (or type), which specifies a storage
         format, constraints, and valid range of values. PL/SQL provides a variety of predefined
         datatypes. E.g., integer, floating point, character, Boolean, date, collection, reference, and
         LOB types. In addition, PL/SQL lets you define your own subtypes.

         The default types in PL/SQL are: number, char, boolean, and date.
         Declaring variables:
         DECLARE
                part_no NUMBER(6);
                part_name VARCHAR2(20);
                in_stock BOOLEAN;
                part_price NUMBER(6,2);
                part_desc VARCHAR2(50);
                hours_worked NUMBER := 40; --declare and assign value

         The %TYPE attribute:
         PL/SQL uses the %TYPE attribute to declare a variable based on definitions of columns in a
         table. Therefore, if a column’s attributes change, the variable’s attributes (data type) will also
         change. The obvious benefits are: data independence, reduces maintenance costs and allows
         programs to change according to changes in the table.


    Prof. Mukesh N Tekwani                                               mukeshtekwani@hotmail.com
Chap 1. Introduction To PL/SQL       5


     Example:
     credit REAL(7,2);
     debit credit%TYPE;

     NOT NULL causes creation of a variable or a constant that cannot be assigned a null value. If
     a null value is assigned to such a variable or constant, Oracle will generate an exception
     condition (error). Every variable or constant declared as NOT NULL must be followed by a
     PL/SQL statement that assigns a value to the variable or constant.
     Example:
     acct_id INTEGER(4) NOT NULL := 9999;

     Assigning values to variables:
     • Values are assigned to variables by using the assignment operator := (i.e. the colon sign,
        followed by the equal sign).
     • Selecting or fetching table data values into variables.

     Declaring Constants:
     A constant is declared by adding the keyword constant to the variable name and assigning it a
     value immediately. Values of constants cannot be changed in PL/SQL block.

     RAW types: These are used to store binary data.

     LOB Types: The LOB (large object) datatypes BFILE, BLOB, CLOB, and NCLOB let you
     store blocks of unstructured data (such as text, graphic images, video clips, and sound
     waveforms) up to four gigabytes in size.

 7   Write a note on the conditional control structure in PL/SQL .
     The conditional structures in PL/SQL are:
     1. IF ….ENDIF statement
     2. IF..THEN..ELSE..END IF statement.
     3. IF..THEN..ELSIF..ELSE…END IF statement (Note: observe carefully the spelling of
        ELSIF)

     Example: Write a PL/SQL block that will accept an account number from tehuser, check is
     the user’s balance is less than the minimum balance, and only then deduct Rs 200 as penalty
     from the balance. The process is fired on the ACCT_MST table.

     DECLARE
     /* we first declare the memory variables and constants */
     mCURBAL NUMBER (11,2);
     mACCTNO VARCHAR2(7); /* VARCHAR2datatype stores variable length character data */
     mPENALTY NUMBER(4) := 200;
     mMINBAL NUMBER (7, 2) := 10000.00;

     BEGIN
     /* accept the account number from the user */
     mACCTNO := &ACCTNO;

     /* retrieve the current balance from the ACCT_MST table */
     SELECT URBAL INTO mCURBAL FROM ACCT_MST WHERE ACCTNO = mACCTNO

mukeshtekwani@hotmail.com                                               Prof. Mukesh N. Tekwani
6    Chap 1. Introduction To PL/SQL


         /* Now check if the balance is less than minimum balance and if so, deduct 200 as penalty */
         IF mCURBAL < mMINBAL THEN
               UPDATE ACCT_MST SET CURBAL = CURBAL – mPENALTY
               WHERE ACCTNO = mACCTNO;
         END IF;
         END;
         /

         Example2: Using a Simple IF-THEN-ELSE Statement
         DECLARE
              sales NUMBER(8,2) := 12100;
              quota NUMBER(8,2) := 10000;
              bonus NUMBER(6,2);
              emp_id NUMBER(6) := 120;
         BEGIN
              IF sales > (quota + 200) THEN
                      bonus := (sales - quota)/4;
              ELSE
                      bonus := 50;
              END IF;
              UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
         END;
         /

         Example3: Using the IF-THEN-ELSEIF Statement
         DECLARE
              sales NUMBER(8,2) := 20000;
              bonus NUMBER(6,2);
              emp_id NUMBER(6) := 120;
         BEGIN
              IF sales > 50000 THEN
                      bonus := 1500;
              ELSIF sales > 35000 THEN
                      bonus := 500;
              ELSE
                      bonus := 100;
              END IF;
              UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
         END;
         /

         Example4: Using the CASE statement
         SQL> DECLARE
          2 grade CHAR(1);
          3 BEGIN
          4 grade := 'B';
          5
          6 CASE grade
          7   WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
          8   WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');

    Prof. Mukesh N Tekwani                                            mukeshtekwani@hotmail.com
Chap 1. Introduction To PL/SQL        7


      9   WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');
     10   WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');
     11   WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');
     12   ELSE DBMS_OUTPUT.PUT_LINE('No such grade');
     13 END CASE;
     14 END;
     15 /

     Output:
     Very Good

     PL/SQL procedure successfully completed.

     SQL>


 8   Write a note on Iterative Control statements in PL/SQL .
     Iterative statements execute a set of statements (or a loop) repeatedly. The keyword LOOP is
     used before the first statement in the sequence of statements that has to be repeated. The
     keyword END LOOP is used to indicate the end of a loop. There must be a conditional
     statement that can control the number of times the loop is executed else the loop will go on
     forever (infinite loop).

     Syntax:
     LOOP
      sequence_of_statements
     END LOOP;

     With each iteration of the loop, the sequence of statements is executed, then control resumes at
     the top of the loop. You use an EXIT statement to stop looping and prevent an infinite loop.
     You can place one or more EXIT statements anywhere inside a loop, but not outside a loop.
     There are two forms of EXIT statements: EXIT and EXIT-WHEN.

     The following are important steps to be followed while using this simple looping structure.
     1) Initialise a variable before the loop body.
     2) Increment the variable in the loop.
     3) Use an EXIT WHEN statement to exit from the Loop based on a condition. If you use an
        EXIT statement without WHEN condition, the statements in the loop is executed only
        once.

     Example 1: Create a simple loop so that a message is displayed when a loop exceeds a
     particular value.
     DECLARE
           n NUMBER := 0;
     BEGIN
           LOOP
                 n := n + 2;
                 EXIT WHEN n > 10;
           END LOOP:
           dbms_output.put_line (‘Loop exited as n has reached the value ‘ || TO_CHAR(n));
     END;

mukeshtekwani@hotmail.com                                                  Prof. Mukesh N. Tekwani
8    Chap 1. Introduction To PL/SQL


         /

         In this code, the statement dbms_output.put_line() is used to display ay message you want, on the
         screen. Here, put_line is the procedure that generates the output on the screen and dbms_output is the
         package to which put_line() belongs.

         Example 2: This illustrates the use of the EXIT statement in looping.
         DECLARE
               credit_rating NUMBER := 0;
         BEGIN
               LOOP
                        credit_rating := credit_rating + 1;
                        IF credit_rating > 3 THEN
                                EXIT; -- exit loop immediately
                        END IF;
               END LOOP;
               -- control resumes here
               DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating));
               IF credit_rating > 3 THEN
                        RETURN;          -- use RETURN not EXIT when outside a LOOP
               END IF;
               DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating));
         END;
         /

         The RETURN statement immediately ends the execution of a subprogram and returns control
         to the caller.

         The WHILE loop:
         Syntax:
         WHILE <condition>
         LOOP
               <action>
         END LOOP;

         Example 3: Write a PL/SQL code block to calculate the area of a circle for radius varying
         between 3 and 7. Store the corresponding radius and area values in an empty table named
         AREAS, consisting of columns RADIUS and AREA.

         Step 1: We first create the table AREAS as follows:
         CREATE TABLE AREAS (radius NUMBER(5), area NUMBER(14, 2));

         Step 2: PL/SQL code:

         DECLARE
              pi CONSTANT NUMBER(4,2) :=3.14;
              radius NUMBER(5);
              area NUMBER (14, 2);
         BEGIN
              radius := 3;
              WHILE radius <= 7
              LOOP
    Prof. Mukesh N Tekwani                                                  mukeshtekwani@hotmail.com
Chap 1. Introduction To PL/SQL       9


                 area := pi * power(radius, 2);
                 INSERT INTO AREAS VALUES (radius, area);
                 radius := radius + 1;
            END LOOP;
     END;
     /

     Output:
     SQL> select * from areas
      2 ;

        RADIUS      AREA
     ----------    ----------
            3      28.26
            4      50. 24
            5      78.5
            6      113.04
            7      153.86

     The FOR loop:
     As in other programming languages the 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 reaches the
     value of the end integer.
     Syntax:
     FOR var IN startval...endval
            LOOP statements;
     END LOOP;

     The variable in the FOR statement need not be declared. The increment value cannot be
     specified and the variable always increments by 1.

     Example : Using the FOR-LOOP
     DECLARE
           n NUMBER := 10;
     BEGIN
           FOR i IN 1..n LOOP
           DBMS_OUTPUT.PUT_LINE(i);
       END LOOP;
     END;
     /

     Example: Write a PL/SQL code to reverse a number. E.g., the number 3718 becomes
     8173.
     DECLARE
           orgnum VARCHAR(5) := ‘3718’;
           numlen NUMBER(2);
           revnum VARCHAR(5);
     BEGIN
           numlen := length(orgnum);

mukeshtekwani@hotmail.com                                             Prof. Mukesh N. Tekwani
10    Chap 1. Introduction To PL/SQL


                 /* Now we initialize the loop so that it repeats the number of times equal to the length
                 of the original number. Since the number must be inverted, the loop should start from
                 the last digit and store it */

                 FOR ctr IN REVERSE 1..numlen
                 LOOP
                       revnum := revnum || SUBSTR(orgnum, ctr, 1);
                 END LOOP;
                 DBMS_OUTPUT.PUT_LINE(‘The original number is ‘ || orgnum);
                 DBMS_OUTPUT.PUT_LINE(‘The reversed number is ‘ || revnum);
          END;
          /


      9   Write a note on Sequential Control statement (GOTO) in PL/SQL and the use of the
          NULL statement.
          The sequential control statement in PL/SQL is the GOTO statement. By default, statements are
          executed sequentially (one after the other) but sometimes it may be necessary to change this
          normal sequential flow. This statement changes the flow of control in a PL/SQL block.

          The block of code to which control must be transferred in this way is marked with a tag. The
          GOTO statement makes use of this user-defined name or tag to jump into that block of code.
          The important point to note is that the label must appear before an executable statement.

          Syntax:
          GOTO <codeblock name>;
          Example:
          GOTO dogracing;

          Write a PL/SQL code to achieve the following: If no transactions have taken place in the last
          365 days, then mark the bank account as inactive and then record the account number, the
          opening date, and the type of account in the INACTIVEMASTER table.

          Step1:
          CREATE TABLE INACTIVEMASTER
          (      ACCTNO VARCHAR2(10),
                 OPENDT DATE,
                 TYPE VARCHAR2(2)
          );


          Step 2:
          Now we create the PL/SQL code:

          DECLARE
               mACCTNO VARCHAR2(10);
               mANS VARCHAR2(3);
               mOPENDT DATE;
               mTYPE VARCHAR2(2);
          BEGIN

     Prof. Mukesh N Tekwani                                             mukeshtekwani@hotmail.com
Chap 1. Introduction To PL/SQL        11


            /* Accept the account number from the user */
            mACCTNO := &mACCTNO;
            SELECT ‘YES’ INTO mANS FROM TRANSMSTR WHERE ACCTNO =
            mACCTNO GROUP BY ACCTNO HAVING MAX(SYSDATE – DT) > 365;

            /* If no transactions have taken place in the last 365 days, control is transferred to a
            user-labelled section of the code */
            IF mANS = ‘yes’ THEN
                    GOTO mark_status;
            ELSE
                    DBMS_OUTPUT.PUT_LINE(‘Account number ‘ || mACCTNO || ‘is active’);
            END IF;

            <<mark_status>>
            UPDATE ACCTMSTR STATUS = ‘I’ WHERE ACCTNO = mACCTNO;

            SELECT OPNDT, TYPE INTO mOPNDT, mTYPE FROM ACCTMSTR
            WHERE ACCTNO = mACCTNO;

            INSERT INTO INACTIVEMASTER (ACCTNO, OPNDT, TYPE)
            VALUES (mACCTNO, mOPNDT, mTYPE);

            dbms_output.put_line(‘Account Number: ‘ || mACCTNO || ‘is marked as inactive’);
     END;
     There are some restrictions on where the GOTO statement is allowed. A GOTO statement
     cannot branch into an IF statement, CASE statement, LOOP statement, or sub-block. For
     example, the following GOTO statement is not allowed:

     BEGIN
      ...
      GOTO update_row;            -- can't branch into IF statement
      ...
      IF valid THEN
          ...
          <<update_row>>
          UPDATE emp SET ...
      END IF;
     END;

     The NULL statement:
     The NULL statement does nothing other than pass control to the next statement. The following
     code demonstrates the use of the NULL statement:

     DECLARE
      done BOOLEAN;
     BEGIN
      ...
      FOR i IN 1..50 LOOP
          IF done THEN
            GOTO end_loop;

mukeshtekwani@hotmail.com                                                Prof. Mukesh N. Tekwani
12    Chap 1. Introduction To PL/SQL


            END IF;
            ...
           <<end_loop>> -- not allowed
           END LOOP; -- not an executable statement
          END;

          The label end_loop in the above example is not allowed because it does not precede an
          executable statement. We solve this problem by using the NULL statement as follows:

          FOR i IN 1..50 LOOP
           IF done THEN
               GOTO end_loop;
           END IF;
           ...
          <<end_loop>>
          NULL;         -- an executable statement
          END LOOP;

      9   Write PL/SQL code to check whether a number is a prime number.
          SQL> DECLARE
            2 p VARCHAR2(30);
            3 n INTEGER := 37;
            4 BEGIN
            5 FOR j in 2..ROUND(SQRT(n)) LOOP
            6    IF n MOD j = 0 THEN
            7     p := ' is not a prime number';
            8     GOTO print_now;
            9    END IF;
           10 END LOOP;
           11
           12 p := ' is a prime number';
           13
           14 <<print_now>>
           15 DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
           16 END;
           17 /
          37 is a prime number

          PL/SQL procedure successfully completed.

          SQL>




     Prof. Mukesh N Tekwani                                      mukeshtekwani@hotmail.com

Más contenido relacionado

La actualidad más candente

Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideSrinimf-Slides
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to DatabaseSiti Ismail
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academythewebsacademy
 
Relational database- Fundamentals
Relational database- FundamentalsRelational database- Fundamentals
Relational database- FundamentalsMohammed El Hedhly
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introductionSmriti Jain
 
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...Edureka!
 
Simple xml in .net
Simple xml in .netSimple xml in .net
Simple xml in .netVi Vo Hung
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)Syed Hassan Ali
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Punjab University
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statmentsrehaniltifat
 

La actualidad más candente (20)

Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Mysql
MysqlMysql
Mysql
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
SQL - RDBMS Concepts
SQL - RDBMS ConceptsSQL - RDBMS Concepts
SQL - RDBMS Concepts
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
MYSQL
MYSQLMYSQL
MYSQL
 
Database
DatabaseDatabase
Database
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Relational database- Fundamentals
Relational database- FundamentalsRelational database- Fundamentals
Relational database- Fundamentals
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
 
Simple xml in .net
Simple xml in .netSimple xml in .net
Simple xml in .net
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
 

Similar a Pl sql-ch1

PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPTSujayaBiju
 
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptOracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptDheerajKashnyal
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5Pranab Dasgupta
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxshivanikaale214
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_materialgayaramesh
 

Similar a Pl sql-ch1 (20)

PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
pl_sql.ppt
pl_sql.pptpl_sql.ppt
pl_sql.ppt
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Pl sql
Pl sqlPl sql
Pl sql
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
 
Pl sql
Pl sqlPl sql
Pl sql
 
Pl sql
Pl sqlPl sql
Pl sql
 
Pl sql
Pl sqlPl sql
Pl sql
 
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.pptOracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
Oracle_PLSQL_basic_tutorial_with_workon_Exercises.ppt
 
Dbms 2011
Dbms 2011Dbms 2011
Dbms 2011
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
 
Oracle etl openworld
Oracle etl openworldOracle etl openworld
Oracle etl openworld
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and TriggerB.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
 
Unit 4 rdbms study_material
Unit 4  rdbms study_materialUnit 4  rdbms study_material
Unit 4 rdbms study_material
 

Más de Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Más de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Último

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Último (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Pl sql-ch1

  • 1. Chap 1. Introduction To PL/SQL 1 1. Introduction To PL/SQL 1. What is PL/SQL? What are the disadvantages of SQL? PL/SQL stands for Procedural Language extension to SQL. PL/SQL is a 3GL which extends SQL by adding programming capabilities, such as programming structures and subroutines, similar to those available in high-level languages. Thus, PL/SQL is a super set of SQL. PL/SQL is a block-structured language i.e., each bock can perform one logical unit of a job. PL/SQL is used for server-side and client-side development. PL/SQL is also used to develop applications for browsers. SQL is a natural language for database management system but some of the drawbacks of SQL are as follows: 1. SQL does not have the capabilities of programming languages such as looping, branching, checking for conditions, etc. These capabilities are important before data storage. 2. SQL does not have error-handling capabilities. While processing or executing a SQL statement if an error occurs, Oracle displays its own error messages. 3. SQL statements are passed to the Oracle engine, one at a time. Every time a statement is executed, a call is made to the engine’s resources. This decreases the data processing speed as repeated calls must be made to the network. 2. What are the advantages of PL/SQL? PL/SQL is used in most Oracle products. The advantages of PL/SQL are as follows: 1. Development tool: PL/SQL is a development tool. It supports SQL data management. 2. OOPs: PL/SQL has support for object-oriented programs and this provides the advantages of data encapsulation or data hiding. 3. Better Performance: When a PL/SQL block is processed then the entire block is sent to the server and not just individual statements. So if a PL/SQL block contains many SQL statements, then it is treated as one call to the server. If PL/SQL is not used then each SQL statement will result in a separate call to the database server. 4. Improved error handling: PL/SQL permits user-friendly error messages to be displayed instead of the standard cryptic Oracle error messages. 5. Variables can be declared and used in blocks of code. These variables can be used to store intermediate values of calculations or query processing and used later. Calculation can be done and stored in Oracle tables. 6. Portability: Applications developed in PL/SQL are portable across any platform – hardware and software, including operating systems. 7. Higher Productivity: Users can do procedural programming. 8. Integration with Oracle: PL/SQL supports all SQL datatypes. 9. Support for developing web applications and pages. 10. Access to pre-defined packages. 3 Explain the generic 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 Declare section (optional): The Declaration section of a PL/SQL Block starts with the mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 2. 2 Chap 1. Introduction To PL/SQL reserved keyword DECLARE. This section is optional and is used to declare any variables, constants, records and cursors, which are used to manipulate data in the execution section. • The Begin or Execution section: This section begins with the keyword BEGIN and ends with the keyword END. It consists of a set of SQL and PL/SQL statements which describe processes that have to be applied to the table data. This section contains statements for data manipulation, looping, branching and data retrieval. • The Exception (or Error) Handling section (optional) – 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. • A typical code block looks like this: DECLARE Declaration of Variables, constants, cursors, etc BEGIN SQL executable statements and PL/SQL executable statements EXCEPTION SQL block to handle errors that may arise due to execution of code in the BEGIN block. END; / Note the / sign at the end of the code. This tells Oracle to run the block. If the procedure is completed successfully, Oracle generates the following message: “PL/SQL procedure completed successfully”. 4 Explain the PL/SQL Execution environment / PL/SQL architecture • The PL/SQL engine is a part of the Oracle engine. The Oracle engine can process individual SQL statements and also PL/SQL blocks. • Blocks of code are sent to the PL/SQL engine where the procedural statements are executed and the SQL statements are sent to the SQL executor in Oracle engine. • When a number of SQL statements are combined into a PL/SQL block, the call to the Oracle engine is made only once. This process is illustrated below: PL/SQL block of code Oracle Engine DECLARE Procedural statements; PL/SQL Engine BEGIN Procedural Statements; SQL statements; EXCEPTIONS SQL statement Executor SQL statements; END The PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL blocks and subprograms. The engine can be installed in an Oracle server or in an Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 3. Chap 1. Introduction To PL/SQL 3 application development tool such as Oracle Forms. The PL/SQL engine executes procedural statements but sends SQL statements to the SQL engine in the Oracle database. This is shown in the following figure: 5 Write a note on PL/SQL Character Set. Character set of PL/SQL is as follows: upper- and lower-case letters A .. Z and a .. z numerals 0 .. 9 symbols ( ) + - * / < > = ! ~ ^ ; : . ' @ % , " # $ & _ | { } ? [ ] tabs, spaces, and carriage returns Lexical units: Words used in PL/SQL are called lexical units. Blank spaces have no effect on the PL/SQL block. E.g., IF x > y THEN max := x; ELSE max := y; END IF; Compound symbols used in PL/SQL are >= <= != || >> << := ** Literals: It is a numeric value or a character string. Numeric Literal: These can be either integer or float. E.g., 35, 3.142 Character literal: It consists of a single character enclosed between single quotes sign. E.g. ‘A’. String Literal: These are characters stored in single quotes. E.g., ‘Mumbai’. If a single quote character must itself be a part of the string literal, than it must appear twice, e.g., ‘Mumbai’’s weather is good’. Logical (Boolean) literal: These are predetermined constants with values of TRUE, FALSE or NULL. Comments The PL/SQL compiler ignores comments, but we should put comments to improve code readability and maintenance. PL/SQL supports two comment styles: single-line and multi-line. Single-Line Comments: Single-line comments begin with a double hyphen (--) anywhere on a line and extend to the end of the line. A few examples are: mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 4. 4 Chap 1. Introduction To PL/SQL -- begin processing SELECT sal INTO salary FROM emp -- get current salary WHERE empno = emp_id; bonus := salary * 0.15; -- compute bonus amount Comments can appear within a statement at the end of a line. While testing or debugging a program, you might want to disable a line of code. The following example shows how you can "comment-out" the line: -- DELETE FROM emp WHERE comm IS NULL; Multi-line Comments Multi-line comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines. This is similar to C or Java style. Examples are: BEGIN ... /* Compute a 15% bonus for top-rated employees. */ IF rating > 90 THEN bonus := salary * 0.15 /* bonus is based on salary */ ELSE bonus := 0; END IF; ... /* The following line computes the area of a circle using pi, which is the ratio between the circumference and diameter. */ area := pi * radius**2; END; 6 Write a note on PL/SQL data types. Every constant, variable, and parameter has a datatype (or type), which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined datatypes. E.g., integer, floating point, character, Boolean, date, collection, reference, and LOB types. In addition, PL/SQL lets you define your own subtypes. The default types in PL/SQL are: number, char, boolean, and date. Declaring variables: DECLARE part_no NUMBER(6); part_name VARCHAR2(20); in_stock BOOLEAN; part_price NUMBER(6,2); part_desc VARCHAR2(50); hours_worked NUMBER := 40; --declare and assign value The %TYPE attribute: PL/SQL uses the %TYPE attribute to declare a variable based on definitions of columns in a table. Therefore, if a column’s attributes change, the variable’s attributes (data type) will also change. The obvious benefits are: data independence, reduces maintenance costs and allows programs to change according to changes in the table. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 5. Chap 1. Introduction To PL/SQL 5 Example: credit REAL(7,2); debit credit%TYPE; NOT NULL causes creation of a variable or a constant that cannot be assigned a null value. If a null value is assigned to such a variable or constant, Oracle will generate an exception condition (error). Every variable or constant declared as NOT NULL must be followed by a PL/SQL statement that assigns a value to the variable or constant. Example: acct_id INTEGER(4) NOT NULL := 9999; Assigning values to variables: • Values are assigned to variables by using the assignment operator := (i.e. the colon sign, followed by the equal sign). • Selecting or fetching table data values into variables. Declaring Constants: A constant is declared by adding the keyword constant to the variable name and assigning it a value immediately. Values of constants cannot be changed in PL/SQL block. RAW types: These are used to store binary data. LOB Types: The LOB (large object) datatypes BFILE, BLOB, CLOB, and NCLOB let you store blocks of unstructured data (such as text, graphic images, video clips, and sound waveforms) up to four gigabytes in size. 7 Write a note on the conditional control structure in PL/SQL . The conditional structures in PL/SQL are: 1. IF ….ENDIF statement 2. IF..THEN..ELSE..END IF statement. 3. IF..THEN..ELSIF..ELSE…END IF statement (Note: observe carefully the spelling of ELSIF) Example: Write a PL/SQL block that will accept an account number from tehuser, check is the user’s balance is less than the minimum balance, and only then deduct Rs 200 as penalty from the balance. The process is fired on the ACCT_MST table. DECLARE /* we first declare the memory variables and constants */ mCURBAL NUMBER (11,2); mACCTNO VARCHAR2(7); /* VARCHAR2datatype stores variable length character data */ mPENALTY NUMBER(4) := 200; mMINBAL NUMBER (7, 2) := 10000.00; BEGIN /* accept the account number from the user */ mACCTNO := &ACCTNO; /* retrieve the current balance from the ACCT_MST table */ SELECT URBAL INTO mCURBAL FROM ACCT_MST WHERE ACCTNO = mACCTNO mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 6. 6 Chap 1. Introduction To PL/SQL /* Now check if the balance is less than minimum balance and if so, deduct 200 as penalty */ IF mCURBAL < mMINBAL THEN UPDATE ACCT_MST SET CURBAL = CURBAL – mPENALTY WHERE ACCTNO = mACCTNO; END IF; END; / Example2: Using a Simple IF-THEN-ELSE Statement DECLARE sales NUMBER(8,2) := 12100; quota NUMBER(8,2) := 10000; bonus NUMBER(6,2); emp_id NUMBER(6) := 120; BEGIN IF sales > (quota + 200) THEN bonus := (sales - quota)/4; ELSE bonus := 50; END IF; UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id; END; / Example3: Using the IF-THEN-ELSEIF Statement DECLARE sales NUMBER(8,2) := 20000; bonus NUMBER(6,2); emp_id NUMBER(6) := 120; BEGIN IF sales > 50000 THEN bonus := 1500; ELSIF sales > 35000 THEN bonus := 500; ELSE bonus := 100; END IF; UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id; END; / Example4: Using the CASE statement SQL> DECLARE 2 grade CHAR(1); 3 BEGIN 4 grade := 'B'; 5 6 CASE grade 7 WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); 8 WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 7. Chap 1. Introduction To PL/SQL 7 9 WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); 10 WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); 11 WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); 12 ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); 13 END CASE; 14 END; 15 / Output: Very Good PL/SQL procedure successfully completed. SQL> 8 Write a note on Iterative Control statements in PL/SQL . Iterative statements execute a set of statements (or a loop) repeatedly. The keyword LOOP is used before the first statement in the sequence of statements that has to be repeated. The keyword END LOOP is used to indicate the end of a loop. There must be a conditional statement that can control the number of times the loop is executed else the loop will go on forever (infinite loop). Syntax: LOOP sequence_of_statements END LOOP; With each iteration of the loop, the sequence of statements is executed, then control resumes at the top of the loop. You use an EXIT statement to stop looping and prevent an infinite loop. You can place one or more EXIT statements anywhere inside a loop, but not outside a loop. There are two forms of EXIT statements: EXIT and EXIT-WHEN. The following are important steps to be followed while using this simple looping structure. 1) Initialise a variable before the loop body. 2) Increment the variable in the loop. 3) Use an EXIT WHEN statement to exit from the Loop based on a condition. If you use an EXIT statement without WHEN condition, the statements in the loop is executed only once. Example 1: Create a simple loop so that a message is displayed when a loop exceeds a particular value. DECLARE n NUMBER := 0; BEGIN LOOP n := n + 2; EXIT WHEN n > 10; END LOOP: dbms_output.put_line (‘Loop exited as n has reached the value ‘ || TO_CHAR(n)); END; mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 8. 8 Chap 1. Introduction To PL/SQL / In this code, the statement dbms_output.put_line() is used to display ay message you want, on the screen. Here, put_line is the procedure that generates the output on the screen and dbms_output is the package to which put_line() belongs. Example 2: This illustrates the use of the EXIT statement in looping. DECLARE credit_rating NUMBER := 0; BEGIN LOOP credit_rating := credit_rating + 1; IF credit_rating > 3 THEN EXIT; -- exit loop immediately END IF; END LOOP; -- control resumes here DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating)); IF credit_rating > 3 THEN RETURN; -- use RETURN not EXIT when outside a LOOP END IF; DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating)); END; / The RETURN statement immediately ends the execution of a subprogram and returns control to the caller. The WHILE loop: Syntax: WHILE <condition> LOOP <action> END LOOP; Example 3: Write a PL/SQL code block to calculate the area of a circle for radius varying between 3 and 7. Store the corresponding radius and area values in an empty table named AREAS, consisting of columns RADIUS and AREA. Step 1: We first create the table AREAS as follows: CREATE TABLE AREAS (radius NUMBER(5), area NUMBER(14, 2)); Step 2: PL/SQL code: DECLARE pi CONSTANT NUMBER(4,2) :=3.14; radius NUMBER(5); area NUMBER (14, 2); BEGIN radius := 3; WHILE radius <= 7 LOOP Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 9. Chap 1. Introduction To PL/SQL 9 area := pi * power(radius, 2); INSERT INTO AREAS VALUES (radius, area); radius := radius + 1; END LOOP; END; / Output: SQL> select * from areas 2 ; RADIUS AREA ---------- ---------- 3 28.26 4 50. 24 5 78.5 6 113.04 7 153.86 The FOR loop: As in other programming languages the 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 reaches the value of the end integer. Syntax: FOR var IN startval...endval LOOP statements; END LOOP; The variable in the FOR statement need not be declared. The increment value cannot be specified and the variable always increments by 1. Example : Using the FOR-LOOP DECLARE n NUMBER := 10; BEGIN FOR i IN 1..n LOOP DBMS_OUTPUT.PUT_LINE(i); END LOOP; END; / Example: Write a PL/SQL code to reverse a number. E.g., the number 3718 becomes 8173. DECLARE orgnum VARCHAR(5) := ‘3718’; numlen NUMBER(2); revnum VARCHAR(5); BEGIN numlen := length(orgnum); mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 10. 10 Chap 1. Introduction To PL/SQL /* Now we initialize the loop so that it repeats the number of times equal to the length of the original number. Since the number must be inverted, the loop should start from the last digit and store it */ FOR ctr IN REVERSE 1..numlen LOOP revnum := revnum || SUBSTR(orgnum, ctr, 1); END LOOP; DBMS_OUTPUT.PUT_LINE(‘The original number is ‘ || orgnum); DBMS_OUTPUT.PUT_LINE(‘The reversed number is ‘ || revnum); END; / 9 Write a note on Sequential Control statement (GOTO) in PL/SQL and the use of the NULL statement. The sequential control statement in PL/SQL is the GOTO statement. By default, statements are executed sequentially (one after the other) but sometimes it may be necessary to change this normal sequential flow. This statement changes the flow of control in a PL/SQL block. The block of code to which control must be transferred in this way is marked with a tag. The GOTO statement makes use of this user-defined name or tag to jump into that block of code. The important point to note is that the label must appear before an executable statement. Syntax: GOTO <codeblock name>; Example: GOTO dogracing; Write a PL/SQL code to achieve the following: If no transactions have taken place in the last 365 days, then mark the bank account as inactive and then record the account number, the opening date, and the type of account in the INACTIVEMASTER table. Step1: CREATE TABLE INACTIVEMASTER ( ACCTNO VARCHAR2(10), OPENDT DATE, TYPE VARCHAR2(2) ); Step 2: Now we create the PL/SQL code: DECLARE mACCTNO VARCHAR2(10); mANS VARCHAR2(3); mOPENDT DATE; mTYPE VARCHAR2(2); BEGIN Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 11. Chap 1. Introduction To PL/SQL 11 /* Accept the account number from the user */ mACCTNO := &mACCTNO; SELECT ‘YES’ INTO mANS FROM TRANSMSTR WHERE ACCTNO = mACCTNO GROUP BY ACCTNO HAVING MAX(SYSDATE – DT) > 365; /* If no transactions have taken place in the last 365 days, control is transferred to a user-labelled section of the code */ IF mANS = ‘yes’ THEN GOTO mark_status; ELSE DBMS_OUTPUT.PUT_LINE(‘Account number ‘ || mACCTNO || ‘is active’); END IF; <<mark_status>> UPDATE ACCTMSTR STATUS = ‘I’ WHERE ACCTNO = mACCTNO; SELECT OPNDT, TYPE INTO mOPNDT, mTYPE FROM ACCTMSTR WHERE ACCTNO = mACCTNO; INSERT INTO INACTIVEMASTER (ACCTNO, OPNDT, TYPE) VALUES (mACCTNO, mOPNDT, mTYPE); dbms_output.put_line(‘Account Number: ‘ || mACCTNO || ‘is marked as inactive’); END; There are some restrictions on where the GOTO statement is allowed. A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement, or sub-block. For example, the following GOTO statement is not allowed: BEGIN ... GOTO update_row; -- can't branch into IF statement ... IF valid THEN ... <<update_row>> UPDATE emp SET ... END IF; END; The NULL statement: The NULL statement does nothing other than pass control to the next statement. The following code demonstrates the use of the NULL statement: DECLARE done BOOLEAN; BEGIN ... FOR i IN 1..50 LOOP IF done THEN GOTO end_loop; mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 12. 12 Chap 1. Introduction To PL/SQL END IF; ... <<end_loop>> -- not allowed END LOOP; -- not an executable statement END; The label end_loop in the above example is not allowed because it does not precede an executable statement. We solve this problem by using the NULL statement as follows: FOR i IN 1..50 LOOP IF done THEN GOTO end_loop; END IF; ... <<end_loop>> NULL; -- an executable statement END LOOP; 9 Write PL/SQL code to check whether a number is a prime number. SQL> DECLARE 2 p VARCHAR2(30); 3 n INTEGER := 37; 4 BEGIN 5 FOR j in 2..ROUND(SQRT(n)) LOOP 6 IF n MOD j = 0 THEN 7 p := ' is not a prime number'; 8 GOTO print_now; 9 END IF; 10 END LOOP; 11 12 p := ' is a prime number'; 13 14 <<print_now>> 15 DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p); 16 END; 17 / 37 is a prime number PL/SQL procedure successfully completed. SQL> Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com