Chapter 1
Upcoming SlideShare
Loading in...5

Chapter 1



Need for PL/SQL,Benefits of Using PL/SQL,PL/SQL Block Types and Constructs,PL/SQL Block Structure,Operators and SQL Functions in PL/SQL,Variables,Nested Blocks.

Need for PL/SQL,Benefits of Using PL/SQL,PL/SQL Block Types and Constructs,PL/SQL Block Structure,Operators and SQL Functions in PL/SQL,Variables,Nested Blocks.



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Chapter 1 Chapter 1 Document Transcript

  • Introduction to PL/SQL15 Chapter 1 Introduction to PL/SQL Need for PL/SQL Benefits of Using PL/SQL PL/SQL Block Types and Constructs PL/SQL Block Structure Operators and SQL Functions in PL/SQL Variables Nested Blocks© SQL Star International Ltd 1
  • Introduction to PL/SQL15ObjectivesAt the end of this chapter, you will be able to:  State the need for a procedural language in Oracle  Create PL/SQL blocks  Write nested blocks© SQL Star International Ltd 2
  • Introduction to PL/SQL15Introducing PL/SQLIn the journey so far, you have learnt about the Structured Query Language (SQL).The Oracle software provides a language, Procedural Language/SQL (PL/SQL), whichis an extension of SQL.PL/SQL implements modularity in the codes you write. It allows you to performiterations and handle errors. Features like data hiding and error handling makePL/SQL a state-of-the-art language for databases.PL/SQL also allows data manipulation and SQL query statements to be includedwithin procedural units of code. This makes PL/SQL a powerful transaction processingmechanism.Need for PL/SQLThe requirement for PL/SQL was mainly due to the need to centralize automatedbusiness tasks. For example, if each employee in an organization maintains separateprograms to manage their tasks and updates them at their discretion, it could createconfusions, such as: • New employees or existing employees who are handed over someone else’s work, would have a problem understanding the process followed by the employee vis-à-vis the organization • Any change in business policy or functionality would have to be updated by all the employees individually in all relevant programs.In a centralized functionality this is avoided because all changes need to be made atone place. Changes will get reflected in the relevant codes and all users can accessupdated information.Benefits of Using PL/SQLThe reasons for using PL/SQL are as follows:  Integrating with the Oracle server and Oracle development tools  Implementing performance enhancements in an application  Modularizing the development of programs  Implementing Portability  Declaration of variables  Programming with procedural language control structures  Handling errors© SQL Star International Ltd 3
  • Introduction to PL/SQL15IntegrationPL/SQL plays a key role in:  Oracle server, through stored procedures and functions, database triggers and packages  Oracle development tools, through Oracle Developer component triggersPL/SQL supports the use of SQL datatypes. With direct access provided by SQL,these shared datatypes integrate PL/SQL with the Oracle server data dictionary.Hence, PL/SQL successfully bridges the gap between access to database technologyand the need for procedural language capabilities.Most applications such as Oracle Forms, Oracle Reports and Oracle Graphics, useshared libraries (that hold code), which can be accessed locally or remotely. Toexecute these stored codes, the Oracle tools have their own PL/SQL engine(independent of the engine present in the Oracle server). The engine first filters outthe SQL statements to send them individually to the SQL statement executor in theOracle server. It then processes the remaining procedural statements in theprocedural statement executor in the PL/SQL engine. The procedural statementexecutor processes data, which is already inside the client environment and not inthe database. This reduces the workload on the Oracle server and also the amount ofmemory required.Performance Enhancements of ApplicationsWhen SQL statements are sent to the Oracle server one at a time, each statementresults in a call to the Oracle server, leading to performance overhead and networktraffic. If your application is SQL intensive, then instead of sending SQL statementsindividually to the server, you can put them into one block using PL/SQL and sendthe entire block to the server at one time. This reduces network traffic.PL/SQL also operates with Oracle development tools, thereby adding proceduralprocessing power to these tools and enhancing performance.© SQL Star International Ltd 4
  • Introduction to PL/SQL15Modularized Program DevelopmentPL/SQL programs are made up of one or more blocks. These blocks may beindividual ones or may be nested within another. That is, a block may represent asmall part of another block, which may in turn be part of a whole unit of code. Theunits (procedures, functions or anonymous blocks) making up a PL/SQL program arecalled logical blocks.A diagrammatic representation of modularization is:The advantages associated with modularized development of programs are:  Logical groupings of related statements within blocks  Nesting blocks within larger blocks help build powerful programs  Breaking down complex problems into manageable sets of logical, well-defined modules, which can be implemented within blocksPortabilityPL/SQL is portable. That means, PL/SQL programs can be run wherever the Oracleserver exists. There is no need to tailor them to suit each new environment. This isachieved because PL/SQL is native to the Oracle server, and therefore can be movedto any environment (operating system or platform) that supports the Oracle server.PL/SQL code can also be moved between the Oracle server and Oracle Developerapplications by writing programs and creating libraries in different environments.© SQL Star International Ltd 5
  • Introduction to PL/SQL15Variable DeclarationIn PL/SQL, you can declare variables:  To use them in SQL and procedural statements  Belonging to different data types  Dynamically based on the structure of tables and columns in the databaseProgramming with Procedural Language Control StructuresPL/SQL allows the usage of control structures, which enable you to execute:  Sequence of statements conditionally  Sequence of statements iteratively in a loop  Individually the rows returned by multiple-row queryHandling ErrorsPL/SQL implements error handling functionality by:  Processing Oracle server errors with error handling routines  Declaring your own error conditions and process them with error handlersPL/SQL Block Types and ConstructsThere are two block types and different types of constructs in PL/SQL. A block is aPL/SQL code. A construct is the way in which a block is written to implementdifferent functionality.Block TypesLogical blocks are the basic units of code that make up a PL/SQL program. The twokinds of PL/SQL blocks are:  Anonymous blocks  Named blocks or SubprogramsAnonymous BlocksAnonymous blocks are declared at that point in an application from where they areto be executed and are passed to the PL/SQL engine for execution at runtime. Theseblocks are unnamed blocks. They can be embedded in the iSQL*Plus environment.An application trigger consists of these blocks.SubprogramsUnlike anonymous blocks, named blocks or subprograms are given a name. Theseblocks can be invoked for execution and they can also accept parameters.© SQL Star International Ltd 6
  • Introduction to PL/SQL15Subprograms can be declared as Procedures or Functions. You declare a subprogramas a Procedure to perform an action, and you declare a subprogram as a Function tocompute a value. Subprograms can be written and stored either at the server side orat the client side.ConstructsThere are various PL/SQL program constructs available that use the basic PL/SQLblock. The availability of program constructs depends on the environment in whichthey are executed.The different program constructs are given below.© SQL Star International Ltd 7
  • Introduction to PL/SQL15PL/SQL Block StructureTo write a PL/SQL block, you need to know the different parts of a PL/SQL block andwhat each part should hold. The structure of all PL/SQL blocks is the same. The onlydifference is that, if it is an anonymous block it is not given a name.A PL/SQL block has three sections . They are :  Declarative section  Executable section  Exception handling sectionThe declarative section is where the variables and constants used in the body of theblock are declared. Any cursors or user-defined error handlers that are used in thebody are declared here. This section is optional.The executable section holds the set of statements or the logic of the tasks that areto be performed. You can include SQL statements to make changes to the databaseand PL/SQL statements to manipulate data in the block. The statements in this blockare enclosed within the keywords BEGIN and END. This section is mandatory.The last section of a block is the exception section. Here a set of statements iswritten to handle any errors that might occur when the statements in the executablesection are being executed. This section is optional .© SQL Star International Ltd 8
  • Introduction to PL/SQL15The diagramatic expression of PL/SQL block structure is given below.The syntax for writing a PL/SQL block is: DECLARE <variable name> datatype(size); BEGIN SQL statements; PL/SQL statements; EXCEPTION WHEN <exception name> THEN … END; /Some points that will help you write a block:  A line of PL/SQL text which contains group of characters known as lexical units. These units are classified as follows:  Delimiters are simple or compound symbols that have a special meaning to PL/SQL. The following table presents both the simple as well as the compound symbols:© SQL Star International Ltd 9
  • Introduction to PL/SQL15  Identifiers are used to name PL/SQL program constructs such as Constants, Variables and Exceptions. The following points need to be kept in mind while using identifiers: • Identifiers can be up to 30 characters in length, but ensure they start with an alphabet. • Do not give the same name for the identifiers as the name of columns in a table used in the block. If so, then the Oracle server assumes that the table column is being referred. • An identifier consists of a letter, followed (optional) by other letters, numerals, underscores, dollar signs and number signs. The following characters are however illegal: Abc&efg – illegal ampersand Abc-efg – illegal hyphen Abc/efg – illegal slash Abc efg – illegal space • Identifiers should not be reserved words except when they are used within double quotes, for instance “INSERT”.  Literals are made up of definite values such as character, numeric, string or Boolean values, not represented by identifiers. These are case sensitive.© SQL Star International Ltd 10
  • Introduction to PL/SQL15Literals are of two types: • Character literals: are all the printable characters such as letters, numerals, spaces, and special symbols. Specify character literals in single quotes. • Numeric literals: are represented either by a simple value such as –12 or by a scientific notation such as 3E6. Comments are extra information given by the programmer to improve readability in a code, to enable documenting in each phase and debugging. PL/SQL code can be commented in two ways: • Single line comment represented by -- • Multi line comment represented by /* */  Use a semicolon (;) at the end of all SQL and PL/SQL control statements and the END keyword.  Do not use semicolons after the keywords DECLARE, BEGIN and EXCEPTION.  Increase the readability of the block by writing the keywords in uppercase.  Use a slash (/) to terminate a PL/SQL block on a line by itself.Using Quotes in LiteralsOracle 10g allows you to define your own string delimiters to remove the need todouble up any single quotes. SET SERVEROUTPUT ON BEGIN --original code DBMS_OUTPUT.PUT_LINE(‘He is New Jersey Library ‘’s Member!’); -- using quote symbol DBMS_OUTPUT.PUT_LINE(q’# He is New Jersey Library‘s Member!#’); DBMS_OUTPUT.PUT_LINE(q’[ He is New Jersey Library‘s© SQL Star International Ltd 11
  • Introduction to PL/SQL15 Member !]’); END; / He is New Jersey Library‘s Member! He is New Jersey Library‘s Member! He is New Jersey Library‘s Member ! PL/SQL procedure successfully completedOperators in PL/SQLThe following operators are supported in PL/SQL:  Arithmetic  Logical  Relational or Comparison  Concatenation  Exponentiation [Represented by (**)]SQL Functions in PL/SQL StatementsAll the SQL functions can also be used in procedural statements in a block.These include:  Single-row number and character functions  Datatype conversion functions  Date functions  Timestamp functions  GREATEST and LEAST functionsThe functions that cannot be used in procedural statements are:  DECODE  Group functions like AVG, MIN, MAX, COUNT, SUM, STDDEV and VARIANCE. These functions work only on a group of rows in a table and hence, they can be used only with the SQL statements in a PL/SQL block.VariablesA variable are named memory locations used to store data temporarily. The datastored in variables is used in the blocks and then processed. When the processing iscompleted, the data held in the variables may be written to the database or simplyerased in case of session wide variables.Why is a Variable used?A Variable stores data temporarily. It manipulates the stored data and performscalculations with the data without accessing the database. Once declared, variables© SQL Star International Ltd 12
  • Introduction to PL/SQL15can be used repeatedly in an application by referencing them in other statements inthe block.When variables are declared using %TYPE and %ROWTYPE (more information isprovided later in the chapter), you are infact basing the variable declaration on thecolumn definition of a table. In this case, if the column definition changes, then thevariable declarations also changes accordingly. This helps in data independence,reduces maintenance cost and allows the program to adjust to the new businesslogic.How to handle variables in PL/SQL?In a PL/SQL block, variables are:  Declared and initialized in the declarative section of the block.  Assigned new values in the executable section. On doing so, the existing value is replaced with the newly assigned value. Care must be taken to see that a variable being referred to is already declared in the declarative section. Forward references cannot be made.Types of VariablesVariables are of two types. They are:  PL/SQL variables  Non-PL/SQL variablesPL/SQL VariablesPL/SQL variables have a data type that specifies a storage format, constraints andalso valid range of values.The data types used to declare PL/SQL variables are:  Scalar data types are those that correspond to database column types. These data types hold only a single value. The base scalar data types include:  CHAR  VARCHAR2  LONG  LONG RAW  NUMBER  BINARY_INTEGER  PLS_INTEGER  BINARY_FLOAT  BINARY_DOUBLE  BOOLEAN  DATE  TIMESTAMP  TIMESTAMP WITH TIMEZONE  TIMESTAMP WITH LOCAL TIMEZONE  INTERVAL YEAR TO MONTH  INTERVAL DAY TO SECOND© SQL Star International Ltd 13
  • Introduction to PL/SQL15Binary_Float and Binary_Double are the two new Datatypes introduced inOracle10g.They represent floating point numbers in IEEE 754 format (Institute ofElectrical and Electronic Engineers) and require 5 byte and 9 bytes to store thevalues respectively. IEEE format s supported by most of the computer systemoperating through native processor instructions thereby helping us to carry outcomplex computations using floating point data. Composite data types are those that are defined by users. They enable you to manipulate groups of data in PL/SQL blocks Reference data types are those that hold values pointing to other objects. These are also known as pointers. LOB (large object) data types: are those that hold values, which specify thelocation of large objects such as graphic images. These values are known as locators.Large objects are stored in the same database as the table but not within the table.LOB data type allows you to store unstructured data of a maximum of 8-128terabytes. This data could be a movie clip or a graphic image or a sound wave form.LOBs are further classified into:  CLOB (Character Large Objects) is used to store large blocks of character data of a single byte.  BLOB (Binary Large Object) is used to store large binary objects within the database.  BFILE (Binary File) is used to store large binary objects that are in the operating system files outside the database.  NCLOB (National Language Character Large Objects), are used to store large blocks of NCHAR data that may be single-byte or fixed-width multiple bytesThe syntax for declaring PL/SQL variables is: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];Where,identifier is the name assigned to the variable declared.CONSTANT specifies a constraint that the value of the variable cannot change.Constant variables must be initialized. While declaring a variable as a constant, theCONSTANT keyword must precede the datatype specification.DATATYPE specifies the type of data the variable can hold. It could be scalar,composite, reference or LOB datatype.NOT NULL specifies a constraint that the variable must contain a value. Therefore,NOT NULL variables must be initialized.:= is the assignment operator used to assign an expression to a variable. Instead ofthe assignment operator, the DEFAULT expr (expression) can be used to assignvalues to the variables.© SQL Star International Ltd 14
  • Introduction to PL/SQL15By default, all variables are initialized to NULL. To prevent null values, variables areinitialized using the DEFAULT keyword.The following code snippet shows how PL/SQL variables are declared in thedeclarative section of a block: DECLARE FirstName CHAR(20); BranchID CHAR(7) NOT NULL: = ‘09RANNJ’; FeeAmt CONSTANT NUMBER(2): = 15; CatgName CHAR(15) DEFAULT ‘Fiction’;% TYPE AttributeIf you need to store a database column value in a variable or write a value from avariable to a database column, then the data type of the variable needs to be thesame as that of the database column. You can use the %TYPE attribute to declare avariable to be of the same data type as that of a previously declared variable ordatabase column.Incorrect variable data types generate PL/SQL errors during execution. When youwant to declare a variable using a table attribute instead of the datatype the syntaxis <variable_name> table.columnname%TYPEFor example, in case you want to declare a variable that will store the address of alibrary member, you will write in the following syntax: DECLARE Address VARCHAR2(45);But, the above declaration will result in an error when an attempt is made topopulate the variable with address details of members from the database table. Thisis because there is a mismatch in type specification of the variable. The datatypewidth of the vAddress column in table Member is 50, but you have declared it as45. To overcome this, declare the variable using %TYPE attribute as follows: DECLARE Address Member.vAddress%TYPE;This statement declares a variable whose datatype and width is based on thevAddress column.If you want to declare a variable of the same type as a previously declared variablethen the syntax is <variable_name> variable_name%TYPE© SQL Star International Ltd 15
  • Introduction to PL/SQL15Using %TYPE attribute to declare a variable based on a previously declared variable,is illustrated in the section dealing with the iSQL*Plus variables within PL/SQL blocks.Datatype and Variable size is determined when the block is compiled. So even ifthere is a change in the database column datatype the code manages the changeddatatype information.Data Conversion FunctionsIn any programming language generally, we have to deal with different datatypessimultaneously or receive data which is not in the default format. In such cases,Oracle server implicitly converts data into valid datatypes wherever feasible. Explicitconversions come into the scenario where automatic conversions are not possible.Oracle Server takes care of implicit conversion between1. Character and Number2. Character and DateBut how is it done? Let us take an example. DECLARE cons_nfine NUMBER(3):=50; cons_extra_fine VARCHAR2(20):=’5; tot_fine Transaction.nfine%TYPE; BEGIN tot_fine:= cons_nfine+cons_extra_fine; DBMS_OUTPUT.PUT_LINE(‘The total fine payable is Rs.‘||tot_fine); END; /So, did you notice something?Variable cons_nfine is of number datatype and cons_extra_fine is of VARCHAR2datatype. While assigning the result to tot_fine variable, cons_extra_fine isconverted to number by PL/SQL executer and then the operation is performed.© SQL Star International Ltd 16
  • Introduction to PL/SQL15To perform explicit conversion, following built in functions can be used. to_char() to_number() to_date() to_Binary_float() to_Binary_double() DECLARE v_Date date:= to_Date( ‘April 04 2007’,’Month dd YYYY’); BEGIN DBMS_OUTPUT.PUT_LINE(‘You have entered ‘ ||v_Date ||’ asinput’); END; /Example to show the usage of new datatypes. DECLARE l_binary_float BINARY_FLOAT; l_binary_double BINARY_DOUBLE; BEGIN l_binary_float := 2.1f; l_binary_double := 2.00001d; DBMS_OUTPUT.PUT_LINE(l_binary_double); DBMS_OUTPUT.PUT_LINE(l_binary_float); l_binary_float := TO_BINARY_FLOAT(2.1); l_binary_double := TO_BINARY_DOUBLE(2.00001); DBMS_OUTPUT.PUT_LINE(l_binary_double); DBMS_OUTPUT.PUT_LINE(l_binary_float); END; /© SQL Star International Ltd 17
  • Introduction to PL/SQL15Non-PL/SQL VariablesSince PL/SQL has neither input nor output capabilities, it relies on the environment inwhich it is executed in order to pass values into and out of a PL/SQL block.The following non-PL/SQL variables can be used within PL/SQL blocks:  Substitution variables  Host variablesSubstitution variables are those that you can use to pass values to a PL/SQL block atruntime. To reference a substitution variable in a block, prefix it with an ampersand(&). Before the block is executed the values for the variables are substituted with thevalues passed.Hence, you cannot input different values for the substitution variables using a loop.The substitution variable can be replaced only by one value.Here is an example showing the use of substitution variables within PL/SQL blocks.Suppose, the library wants to calculate its quarterly income based on its annualincome. To do this, it declares a substitution variable, which would prompt the userto enter the figure of annual income. Based on the value entered, the quarterlyincome would be calculated. DECLARE AnnualIncome NUMBER (7): = &annualinc; QuarterlyInc AnnualIncome%TYPE; -—declaring variable based on previously declared variable using --%TYPE attribute. BEGIN QuarterlyInc:= AnnualIncome/4; DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library is: ’|| QuarterlyInc); END; /In the above block, to display the quarterly income calculated, you can specify theDBMS_OUTPUT.PUT_LINE in the PL/SQL block. DBMS_OUTPUT is an Oracle suppliedpackage and PUT_LINE is a procedure within it. To use this you need to specify theinformation you want printed, in parentheses, following theDBMS_OUTPUT.PUT_LINE command as shown in the above code: DBMS_OUTPUT.PUT_LINE (‘The quarterly income of the library is: ’|| QuarterlyInc);For DBMS_OUTPUT.PUT_LINE to work, you need to run the iSQL*Plus commandSET SERVEROUTPUT ON.iSQL*Plus host variables (also known as bind variables) are used to pass runtimevalues from the PL/SQL block back to the iSQL*Plus environment. These variablescan be referenced in a PL/SQL block by placing a colon(:) before the variable.© SQL Star International Ltd 18
  • Introduction to PL/SQL15The keyword VARIABLE is used to declare a bind variable. The syntax is: VARIABLE <variable_name> datatypeThe syntax to display the variable value is: PRINT <variable_name>Bind variables cannot be referred within the PL/SQL block of a function, procedure ora package.In a PL/SQL block, to differentiate between host variables and declared PL/SQLvariables, prefix the former with a colon(:).The code wherein you had calculated the quarterly income using substitutionvariables can be re-written using host variables as follows: VARIABLE QuarterlyInc NUMBER DECLARE AnnualIncome NUMBER(7):= &AnnInc; BEGIN :QuarterlyInc:= AnnualIncome/4; END; / old 2: AnnualIncome NUMBER(7):= &AnnInc; new 2: AnnualIncome NUMBER(7):= 80000; PL/SQL procedure successfully completed. PRINT QuarterlyInc QUARTERLYINC ------------ 20000The above example shows the Host variable being assigned a value inside a PL/SQLblock. To assign a value to a host variable outside the Pl/SQL block following can bedone:- SQL > VARIABLE QuarterlyInc NUMBER SQL > Exec :QuarterlyInc := 20000 SQL> PRINT QuarterlyInc QUARTERLYINC ------------ 20000© SQL Star International Ltd 19
  • Introduction to PL/SQL15Where,Exec stand for Execute privilege.Nested BlocksPL/SQL allows blocks to be nested wherever you can have an executable statement.[This makes the nested block a statement.] Hence, the executable part of a blockcan be broken down into smaller blocks. Even the exception section can containnested blocks.Variable ScopeIssues that concern references to identifiers can be resolved taking into account theirscope and visibility.By scope, we mean that region of a program unit from which an identifier can bereferenced. For instance, a variable in the declarative section can be referenced fromthe exception section of that block.The diagram shown below illustrates the concept of nested blocks and variablescope. By visibility, we mean© SQL Star International Ltd 20
  • Introduction to PL/SQL15the regions from which an identifier can be referenced without using a qualifiedname.The following code snippet shows how to qualify identifiers: <<outer_blk>> --Block label DECLARE --This is the parent block JoiningDt DATE; BEGIN DECLARE --his is the child block JoiningDt DATE; BEGIN … outer_blk.JoiningDt :=TO_DATE (’20- JAN-1998’, ‘DD-MON-YY’); END; … END; /In the code snippet, a variable with the same name as the variable declared in theouter block is declared in the inner block. To reference the outer block variable in theinner block, the variable is qualified by prefixing it with the block name.Identifiers are considered local to the PL/SQL block in which they are declared, andare considered global to all its sub-blocks. Within the sub-block, only local identifiersare visible because to reference the global identifiers you must use a qualified name.If a block cannot find the identifier declared locally, it will look up to declarativesection of the enclosing block (parent block). However, the block will never lookdown to the enclosed blocks (child blocks).Look at the following code and determine the variable scope: <<OUTER_BLK>> DECLARE vSal NUMBER(8,2) := 50000; vComm NUMBER(8,2) := vSal * 0.10; vNote VARCHAR2(200) := ‘Eligible for commission’; BEGIN DECLARE vSal NUMBER(8,2) := 90000; vComm NUMBER (4) := 0; vAnnualComp NUMBER(8,2) := vSal + vComm; BEGIN vNote := ‘Manager not’||vNote; OUTER_BLK.vComm := vSal * 0.20; END; vNote := ‘Salesman’||vNote; END;© SQL Star International Ltd 21
  • Introduction to PL/SQL15 /Based on the rules of scoping, determine values of:  vNote at position 1  vAnnualComp at position 2  vComm at position 1  OUTER_BLK.vComm at position 1  vComm at position 2  vNote at position 2Guidelines for Writing PL/SQL CodePrograms can be indented using carriage return,tabs and aligning keywords in thesame line at different levels.Writing so, the task of debugging is made simpler.While writing programs we can follow a case convention, though PL/SQL is not casesensitive. For instance:- • All keywords should be written in uppercase. • They must be aligned in the same line. • Table names and column names are to be in Initcap and lower case respectively.Indented programs improve the performance in those cases where similarstatements are to be issued repeatedly because there is no need to parse thestatements again.Let us write a program following all the rules stated above. DECLARE AnnualIncome NUMBER(7):= 60000; QuarterlyInc NUMBER(8,2); BEGIN QuarterlyInc:= AnnualIncome/4; DBMS_OUTPUT.PUT_LINE(‘The Quarterly income is ‘||QuarterlyInc); END; /Here, the keywords are aligned in the same line but at different levels. Thisimproves readability of the code.© SQL Star International Ltd 22
  • Introduction to PL/SQL15SummaryIn this chapter, you have learnt that: PL/SQL bridges gap between SQL and a procedural language.  Two types of PL/SQL blocks are: 1. Anonymous or unnamed blocks which are not stored in database and compiled each time they are executed. 2. Named Blocks which are compiled only once and stored in the database.  The three sections of a PL/SQL Block are: 1. Declarative Section, where all the variables used in the program are declared. This is optional. Keyword: DECLARE 2. Executable Section where actual logic of the program lies. Keyword: BEGIN 3. Exception Section where all the errors are handled. This section is optional. Keyword: EXCEPTION 4. END to end the PL/SQL program.  PL/SQL variables are declared and are accessible only within that PL/SQL block. Non- PL/SQL variables are declared outside the PL/SQL block and are available throughout the session.  Two new datatypes FLOAT and DOUBLE introduced in this release help users in computing complex calculations.  Nesting of blocks is allowed to have good control on the scope of the variables. Nested Blocks can also have exception sections.© SQL Star International Ltd 23
  • Introduction to PL/SQL15Lab Exercises1. Identify whether the following declarations are correct or incorrect: a) DECLARE empID NUMBER(5); b) DECLARE str1, str2, str3 VARCHAR2(20); c) DECLARE hiredate DATE NOT NULL; d) DECLARE on BOOLEAN := 5;2. Create an anonymous block to display the phrase “Welcome to the world ofPL/SQL”.3. Create a block that declares two variables, one of VARCHAR2 type and theother of NUMBER type. Assign the following values to the variables and display theoutput on the screen.© SQL Star International Ltd 24
  • Introduction to PL/SQL154. Write a PL/SQL code to display the ID, Last Name, job ID and salary of anemployee?5. Among the following which datatypes are enhancements of Oracle10g? a) BINARY_INTEGER b) BINARY_FLOAT c) BINARY_DOUBLE6. Display the following text using quote operator q: I’m Oracle certified,you’re not.© SQL Star International Ltd 25