SQL enables us to create, organize, retrieve and maintain data stored in database it does not...

28
SQL SQL enables us to create, organize, retrieve and enables us to create, organize, retrieve and maintain data stored in database it does not provide maintain data stored in database it does not provide the features which a typical programming language the features which a typical programming language offers, such as control-of-flow construct ( sequence, offers, such as control-of-flow construct ( sequence, selection and iteration construct ), or the facility selection and iteration construct ), or the facility to declare and use variables to declare and use variables Though SQL is the natural language of the DBA, it Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when suffers from various inherent disadvantages, when used as a conventional programming language. used as a conventional programming language. Although SQL is a very powerful tool, it's set of Although SQL is a very powerful tool, it's set of disadvantages prevent it from being a fully disadvantages prevent it from being a fully structured programming language. For a fully structured programming language. For a fully structured programming language, Oracle provides structured programming language, Oracle provides PL/SQL. PL/SQL. PL/SQL PL/SQL is Oracle's Procedural Language extension to SQL.

Transcript of SQL enables us to create, organize, retrieve and maintain data stored in database it does not...

SQL SQL enables us to create, organize, retrieve and maintain data stored in enables us to create, organize, retrieve and maintain data stored in database it does not provide the features which a typical programming database it does not provide the features which a typical programming language offers, such as control-of-flow construct ( sequence, selection language offers, such as control-of-flow construct ( sequence, selection and iteration construct ), or the facility to declare and use variablesand iteration construct ), or the facility to declare and use variables

Though SQL is the natural language of the DBA, it suffers from various Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming inherent disadvantages, when used as a conventional programming language.language.

Although SQL is a very powerful tool, it's set of disadvantages prevent it Although SQL is a very powerful tool, it's set of disadvantages prevent it from being a fully structured programming language. For a fully from being a fully structured programming language. For a fully structured programming language, Oracle provides PL/SQL.structured programming language, Oracle provides PL/SQL.

PL/SQL

PL/SQL is Oracle's Procedural Language extension to SQL.

Advantages of PL/SQL Advantages of PL/SQL for the Developer and for the Developer and the Database Administrator the Database Administrator ::

1.1. PL/SQL is development tool that not only supports SQL data PL/SQL is development tool that not only supports SQL data manipulation but also provides facilities of conditional checking, manipulation but also provides facilities of conditional checking, branching and looping.branching and looping.

2.2. PL/SQL sends an entire block of statements to the Oracle engine PL/SQL sends an entire block of statements to the Oracle engine at one time. The communication between the program block and at one time. The communication between the program block and the Oracle engine reduces considerably. This in turn reduces the Oracle engine reduces considerably. This in turn reduces network traffic. network traffic.

3.3. PL/SQL also permits dealing with errors as required, and facilitates PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly messages, when errors are encountered.displaying user-friendly messages, when errors are encountered.

4. PL/SQL allows declaration and use of variables in blocks of code. 4. PL/SQL allows declaration and use of variables in blocks of code. These variables can be used to store intermediate results of a These variables can be used to store intermediate results of a query for later processing, or calculate values and insert them into query for later processing, or calculate values and insert them into an Oracle table later. an Oracle table later.

5. Via PL/SQL, all sorts of calculations can be done quickly and 5. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without the use of the Oracle engine. efficiently without the use of the Oracle engine.

Benefits of PL/SQLBenefits of PL/SQL

IntegrationIntegration

ApplicationApplication

Oracle ServerOracle ServerSharedSharedlibrarylibrary

Benefits of PL/SQLBenefits of PL/SQL

ApplicationApplication Other DBMSsOther DBMSs

ApplicationApplicationOracle with

PL/SQLOracle with

PL/SQL

SQLSQL

SQLSQLSQLSQL

SQLSQL

SQLSQLIF...THENIF...THEN

SQLSQLELSEELSE

SQLSQLEND IF;END IF;SQLSQL

Benefits of PL/SQLBenefits of PL/SQL

Improved maintenanceImproved maintenance Improved data security and integrityImproved data security and integrity Improved performanceImproved performance

AnonymousAnonymousblockblock

AnonymousAnonymousblockblock

ApplicationApplicationtriggertrigger

ApplicationApplicationtriggertrigger

Stored Stored procedure/procedure/

functionfunction

Stored Stored procedure/procedure/

functionfunction

DatabaseDatabasetriggertrigger

DatabaseDatabasetriggertrigger

ApplicationApplicationprocedure/procedure/

functionfunction

ApplicationApplicationprocedure/procedure/

functionfunction

PackagePackagePackagePackage

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

PL/SQL Program ConstructsPL/SQL Program Constructs

PL/SQL Anonymous Block PL/SQL Anonymous Block StructureStructure

DECLARE (optional)DECLARE (optional)Declare PL/SQL objects to be usedDeclare PL/SQL objects to be used

within this blockwithin this block

BEGIN (mandatory)BEGIN (mandatory)Define the executable statementsDefine the executable statements

EXCEPTION (optional)EXCEPTION (optional)Define the actions that take place ifDefine the actions that take place if

an error arisesan error arises

END; (mandatory)END; (mandatory)

Subprogram block structure Subprogram block structure

Header Header IS|ASIS|AS

Declaration sectionDeclaration section BEGINBEGIN

Executable sectionExecutable section EXCEPTION EXCEPTION (optional)(optional)

Exception sectionException section END;END;

PL/SQL The character set:The basic character set includes the following: uppercase alphabets { A - Z } . lowercase alphabets {a-z } numerals { 0 - 9 } `symbols: () + - */ <> = !; : .‘ @ % ,“ # $ ^& _ \ { } ? [ ]Words used in a PL/SQL block are called Lexical Units. Blank spaces can be freely insert between lexical units in a PL/SQL block. The spaces have no effect on the PL/SQL block.

PL/SQL Data TypesBoth PL/ SQL and Oracle have their foundations in SQL. Most PL/SQL data types are native to Oracle's data dictionary. hence, there is a very easy integration of PL/SQL code with the Oracle Engine.

The default data types that can be declared in PL%SQL are number (for storing

numeric data}, char (for storing character data}, date (for storing date and time data},

boolean (for storing TRUE, FALSE or NULL), number, char and date data types can have NULL values.

The %TYPE attribute provides for further integration. PL/SQL can use the %TYPE attribute to declare variables based on definitions of columns in a table.

Use of VariablesUse of Variables

Use variables for:Use variables for: Temporary storage of dataTemporary storage of data Manipulation of stored valuesManipulation of stored values ReusabilityReusability Ease of maintenanceEase of maintenance

Handling Variables in PL/SQLHandling Variables in PL/SQL

Declare and initialize variables in the Declare and initialize variables in the declaration section.declaration section.

Assign new values to variables in the Assign new values to variables in the executable section.executable section.

Pass values into PL/SQL blocks through Pass values into PL/SQL blocks through parameters.parameters.

View results through output variables.View results through output variables.

Variables: `

Variables in PL/SQL blocks are named variables. A variable name must

begin with a character and can be followed by a maximum of 29 other characters.

Reserved words cannot be used as variable names unless enclosed within double quotes. Variables must be separated from each other by at least one space or by a punctuation mark.

Constants:Declaring a constant is similar to declaring a variable except that you have to add the keyword 'constant' and immediately assign a value to it. Thereafter, no further assignments to the constant are possible, while the constant is within the scope of the PL/SQL block.

Naming RulesNaming Rules Two variables can have the same name, Two variables can have the same name,

provided they are in different blocks.provided they are in different blocks. The variable name (identifier) should not The variable name (identifier) should not

be the same as the name of table be the same as the name of table columns used in the block.columns used in the block.

DECLARE empno NUMBER(4);BEGIN SELECT empno INTO empno FROM emp WHERE ename = 'SMITH';END;

DECLARE empno NUMBER(4);BEGIN SELECT empno INTO empno FROM emp WHERE ename = 'SMITH';END;

Assigning Values to VariablesAssigning Values to Variables

v_ename := 'Maduro';v_ename := 'Maduro';

v_hiredate := '31-DEC-98';v_hiredate := '31-DEC-98';

SyntaxSyntax

ExamplesExamples

Set a predefined hiredate for new Set a predefined hiredate for new employees. employees.

Set the employee name to “Maduro.” Set the employee name to “Maduro.”

identifier := expr;identifier := expr;

Variable Initialization and Variable Initialization and KeywordsKeywords

Using:Using: Assignment operator (:=)Assignment operator (:=) DEFAULT keywordDEFAULT keyword NOT NULL constraintNOT NULL constraint

Scalar DatatypesScalar Datatypes

• Hold a single value

• Have no internal components

25-OCT-9925-OCT-99

AtlantaAtlanta

TRUETRUE

256120.08256120.08

Base Scalar DatatypesBase Scalar Datatypes VARCHAR2 (VARCHAR2 (maximum_lengthmaximum_length)) NUMBER [(NUMBER [(precision, scaleprecision, scale)])] DATEDATE CHAR [(CHAR [(maximum_lengthmaximum_length)])] LONGLONG LONG RAWLONG RAW BOOLEANBOOLEAN BINARY_INTEGERBINARY_INTEGER PLS_INTEGERPLS_INTEGER

Scalar Variable DeclarationsScalar Variable Declarations

v_job VARCHAR2(9);v_count BINARY_INTEGER := 0;v_total_sal NUMBER(9,2) := 0;v_orderdate DATE := SYSDATE + 7;c_tax_rate CONSTANT NUMBER(3,2) := 8.25;v_valid BOOLEAN NOT NULL := TRUE;

ExamplesExamples

The %TYPE AttributeThe %TYPE Attribute

Declare a variable according to: Declare a variable according to: • A database column definitionA database column definition• Another previously declared variableAnother previously declared variable

Prefix %TYPE with:Prefix %TYPE with:• The database table and columnThe database table and column• The previously declared variable nameThe previously declared variable name

Declaring Variables Declaring Variables with the %TYPE Attributewith the %TYPE Attribute

ExamplesExamples

v_ename emp.ename%TYPE; v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10;

v_ename emp.ename%TYPE; v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10;

Declaring Boolean VariablesDeclaring Boolean Variables

Only the values TRUE, FALSE, and Only the values TRUE, FALSE, and NULL can be assigned to a Boolean NULL can be assigned to a Boolean variable.variable.

The variables are connected by the The variables are connected by the logical operators AND, OR, and NOT.logical operators AND, OR, and NOT.

The variables always yield TRUE, The variables always yield TRUE, FALSE, or NULL.FALSE, or NULL.

Arithmetic, character, and date Arithmetic, character, and date expressions can be used to return a expressions can be used to return a Boolean value.Boolean value.

Composite DatatypesComposite Datatypes

PL/SQL TABLESPL/SQL TABLES PL/SQL RECORDSPL/SQL RECORDS

LOB Datatype VariablesLOB Datatype Variables

RecipeRecipe(CLOB)(CLOB)

PhotoPhoto(BLOB)(BLOB)

MovieMovie(BFILE)(BFILE)

NCLOBNCLOB

Bind VariablesBind Variables

Server

O/SO/SBind VariableBind Variable

Referencing Non-PL/SQL Referencing Non-PL/SQL VariablesVariables

Referencing Non-PL/SQL Referencing Non-PL/SQL VariablesVariables

Store the annual salary into a Store the annual salary into a SQL*Plus host variable.SQL*Plus host variable.

Reference non-PL/SQL variables as Reference non-PL/SQL variables as host variables.host variables.

Prefix the references with a colon (:).Prefix the references with a colon (:).

Store the annual salary into a Store the annual salary into a SQL*Plus host variable.SQL*Plus host variable.

Reference non-PL/SQL variables as Reference non-PL/SQL variables as host variables.host variables.

Prefix the references with a colon (:).Prefix the references with a colon (:).

:g_monthly_sal := v_sal / 12;:g_monthly_sal := v_sal / 12;

Displaying user Messages on the Screen:Programming tools require a method through which message can be displayed to the user on the VDU screen.DBMS_OUTPUT is a package that includes a number of procedure and functions that accumulate information in a buffer so that it can be retrieved later. These functions can also be used to display messages to the user.PUT_LINE: Put a piece of information in the package buffer followed by an end-of-line marker, It can also be used to display message to the user. Put line expects a single parameter of character data type. if used to display a message, it is the message ‘string’.

To display messages to the user the SERVEROUTPUT should be set to ON.

SERVEROUTPUT is a SQL*PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE function.Syntax SET SERVEROUTPUT (ON/OFF]

Comments:A comment can have two forms'

The comment line begins with a double hyphen (--). The entire line will be treated as a comment.The comment line begins with a slash followed by an asterisk (/*) till the

occurrence of an asterisk followed by a slash (*/). All lines within are treated as comments. This form of specifying comments can be used to span across multiple lines. This technique can also be used to enclose a section of a PL/SQL block that temporarily needs to be isolated and ignored.

SummarySummary

PL/SQL blocks are composed of PL/SQL blocks are composed of the following sections: the following sections: • Declarative (optional)Declarative (optional)• Executable (required)Executable (required)• Exception handling (optional)Exception handling (optional)

A PL/SQL block can be an A PL/SQL block can be an anonymous block, procedure, or anonymous block, procedure, or function. function.

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;