17
UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY: Before PL/SQL was developed users embedded SQL statements in to hot languages like C++ & java PL/SQL version 1.0 had very limited capabilities & it is fully programming language The following features are introduced (1) The transaction control statement SAVEPOINT, ROLLBACK & COMMIT (2) The DML statements INSERT, DELETE & UPDATE (3) The extended data type Boolean, BINARY_INTEGER, PL/SQL records & PL/SQL tables (4) Built- in function characters, numeric, conversion, & date function (5) Built- in packages (6) The control structures sequence, selection & looping (7) Database access through work areas called cursors (8) Error handling (9) Modular programming with procedures & functions (10)Stored procedures, functions, & packages (11) DDL support through the DBMS_SQL packages FUNDAMENTALS OF PL/SQL: An PL/SQL program consist of statements upper or lower case letters in programs Reverse words: The reverse words or key words provided by the language that have a specific use in languages User- defines identifiers: User- define identifiers are used to name variables, constants, procedures, functions, cursors, tables, records, & exceptions The rules for identifiers are (1) The name can be form 1 to 30 characters in length (2) The name must start with a letter (3) Letters (A-Z, a-z), number, the dollar sign ($), the number sign (#) & the underscore ( _ ) are allowed (4) other special characters are not allowed (5) key words cannot be used as the user- define identifiers (6) names must be unique with in a block (7) a names not be the same as the name of the column used in the block

UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

UNIT – IV

PL/SQL: A PROGRAMMING LANGAUGE

HISTORY:

Before PL/SQL was developed users embedded SQL statements in to hot languages like C++ &

java

PL/SQL version 1.0 had very limited capabilities & it is fully programming language

The following features are introduced

(1) The transaction control statement SAVEPOINT, ROLLBACK & COMMIT

(2) The DML statements INSERT, DELETE & UPDATE

(3) The extended data type Boolean, BINARY_INTEGER, PL/SQL records & PL/SQL tables

(4) Built- in function – characters, numeric, conversion, & date function

(5) Built- in packages

(6) The control structures sequence, selection & looping

(7) Database access through work areas called cursors

(8) Error handling

(9) Modular programming with procedures & functions

(10)Stored procedures, functions, & packages

(11) DDL support through the DBMS_SQL packages

FUNDAMENTALS OF PL/SQL:

An PL/SQL program consist of statements upper or lower case letters in programs

Reverse words:

The reverse words or key words provided by the language that have a specific use in languages

User- defines identifiers:

User- define identifiers are used to name variables, constants, procedures, functions, cursors,

tables, records, & exceptions

The rules for identifiers are

(1) The name can be form 1 to 30 characters in length

(2) The name must start with a letter

(3) Letters (A-Z, a-z), number, the dollar sign ($), the number sign (#) & the underscore ( _ ) are

allowed

(4) other special characters are not allowed

(5) key words cannot be used as the user- define identifiers

(6) names must be unique with in a block

(7) a names not be the same as the name of the column used in the block

Page 2: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Literals:

Literals are values that are not represented by user- define identifiers

Literals are of three types

(1) Numeric 100, 3.54, -64.86 or null

(2) Character ‘A’, ‘this is a string’, ’23- may’

(3) Boolean TRUE or FALSE or NULL

BLOCK STRUCTURE:

PL/SQL is a block- structure language

A program can be divided into logical blocks

Block are two types:

(1) An anonymous block

(2) A named block

(1) An anonymous block:

It is a block of code without name

It can be used any where in a program & is sent to the server engine for execution at runtime

(2) A named block:

It is a block of code that is named

A subprogram is named block that can be called & taken as argument

A procedure is a subprogram that can be perform an action whereas a function is a subprogram

that returns a value

The PL/SQL block consist of three sections

(1) A declaration section to declare variables, constants, cursor & PL/SQL

(2) An execution section to manipulate the data in the block

(3) An exception- handling sections handling the error option

The general syntax is

[DECLARE

Declaration of the constants, variables, cursors, and exceptions]

BEGIN

Execution PL/SQL and SQL statements

[EXCEPTION

Actions for error conditions]

END;

COMMENTS:

Page 3: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Comments are used to document program

They are written as the part of program but, they are not executed.

Ex:

-- This is a single document

To write a single document the two dashes ( -- ) are entered at the beginning of the new line

DATA TYPES:

The PL/SQL has four data types :

1. scalar is not made up of group of elements it is atomic in nature

2. composite it is made up of components or elements

3. reference it deals with object

4. LOB it has four various datatypes

The scalar datatype has four major data types

1. character

2. number

3. Boolean

4. date

(1) Character:

Variable with a character datatype can store text the text may include letters, numbers, & special

characters.

CHAR: The CHAR datatype is used for fixed- length string value. The allowable length is

between 1 & 32,767. To declare a variable of the CHAR type in PL/SQL code & that values is to

be inserted in to the tables column the limitation size is 2000 characters

VARCHAR2: The VARCHAR2 is used for variable length string values the allowable length is

between 1 & 32,767. a column in an oracle database with VARCHAR2 type can only take 4000

characters

(2) Number:

PL/SQL has variety of numeric datatypes

Whole number or integer values can be handled by

BINARY_INTEGER (approximately – 231 + 1 to 231, -1 or -2 billion to +2

billion)

INTEGER

Page 4: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

INT

SMALLINT

POSITIVE (a subtype of BINARY_INTEGER – range, 0 to 231)

NATURAL (a subtype of BINARY_INTEGER – range, 1 to 231)

(3) Boolean:

PL/SQL has a logical datatype, Boolean, that is not available in SQL

It is used for Boolean data TRUE, FALSE or NULL

(4) Date:

The date type is special data type that store date & time informations

The date value has specific format DD- MM-YYYY

It stores the following informations

1. century

2. year

3. month

4. day

5. hour

6. minute

7. second

OTHER DATATYPES:

1. NLS (national language support)

2. LOB (Large object) BLOB( Binary large object), CLOB(character large object),

NLOB(number of large object), BFILE (binary file)

(1)NLS (national language support)

this datatype is for characters set in which multiple bytes are used for character representation

(2) LOB (Large object)

it supports large objects datatypes to store large values of character, raw or binary data

It allows up to 4 GB of data

VARIABLE DECLARATION:

Page 5: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

A scalar or constant variable is declared with a datatype & an initial value assignment

The declaration are done in the DECLARE section of a program block

The general syntax is

Variable initialize constant or variable

DECLARE name of the variable

infinitename [ CONSTANT] datatype [NOT NULL] [:=|DEFAULT expression];

Identifier

Anchored declaration:

PL/SQL uses % TYPE attribute to anchor a variable datatype

Another variable or a column in a table can be used for anchoring

The general syntax is

Variable name typeattribute%TYPE [value assignment];

Another variable name

Nested anchoring:

The % TYPE attribute can be nested by Ex:

DECLARE

--source variable v_commission

v_commission Number (7, 2)

-- anchored variable v_total_commissions

ASSIGNMENT OPERATOR:

To assign the value of the variable

The general syntax is

Variablename:= Literal | Variablename|Expression

Ex:

v_num1 := 100

v_num2:= v_num1

v_sum := v_num1 + v_num2

BIND VARIABLES:

It is also known as host variables

These variables are declared in the host SQL*plus environment & aare accessed by a PL/SQL

block

Page 6: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

The general syntax is

VARIABLE Variablename datatype

Ex:

SQL> VARIABLE double NUMBER

SUBSTITUTION VAARIAABLE IN PL/SQL:

PL/SQL does not have any input capabilities in terms of having input statement

Substitution variables of SQL are available in PL/SQL

It have limitation which become apparent in a loop

PRINTING IN PL/SQL:

There is no explicit output statement in PL/SQL

Oracle does not have a built- in packages called DBMS_OUTPUT with the procedure

PUT_LINE to print

The DBMS_OUTPUT is the most frequently used packages because of its capabilities to get

lines from the file & put it to the buffer

Ex:

DBMS_OUTPUT_Line (this line will be displayed);

ARITHMETIC OPERATORS:

Five standard arithmetic operators are available in PL/SQL for calculations

Exponentiation is performed first, multiplication & division are performed next & addition &

subtraction are performed last

If more than one operator of the same priority is present, they are performed from left to right

Whatever in the parentheses is performed first

Arithmetic operators Use

+ Addition

- Subtraction

* Multiplication

/ Division

** Exponentiation

Ex: -2 + 3 * (10 – 2 * 3 ) /6

Page 7: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

1. 2 * 3 = 6 parentheses is performed first

2. 10 – 6 = 4 parentheses is performed first

3. -2 + 3 * ( 4 ) / 6 multiplication is performed

4. -2 + (12) / 6 division is performed

5. -2 + 2 addition is performed

6. 0 result

7.

CONTROL STRUCTURES & EMBEDDED SQL:

CONTROL STRUCTURES:

Three basic control structures

1. sequential structure

2. selection structure

3. looping structure

(1) Sequential structure:

A series of instruction are performed from the beginning to the end in a linear (lengthy) order

(2) Selection structure:

It is also known as decision structure or an IF structure

It involves condition with TRUE or FALSE outcome

(3) Looping structure:

A series of instruction are performed repeatedly

There are different looping statements in different situations.

Selection structure:

There are three selection structure or conditional statement

1. relational

2. logical

3. special operator

(1) Relational operator:

Page 8: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Relational operator Meaning

= Equal to

<> or != Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

(2) Logical operator:

Logical operator Meaning

AND Returns TRUE only if both condition are true

OR Returns TRUE if one or both condition are true

NOT Returns TRUE if the condition is false

(3) Special operators:

(1) IF….THEN….END IF

(2) IF….THEN…. ELSE… END IF

(3) IF….THEN…. ELSE IF… END IF

(4) CAASE….END CASE

(5) Searched CASE

(1) IF….THEN….END IF:

Statement is also known as simple IF statement

It performs action Statement result in condition is TRUE

The general syntax is

IF condition THEN

Action statement

END IF

Ex:

IF age >=18 then

Page 9: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Person is eligible to vote

END IF

(2) IF….THEN…. ELSE… END IF:

IF statement is extension of simple IF statement it provides action statement for the TRUE

outcome as well as for the FALSE outcome

The general syntax is

IF condition THEN

Action statement1

ELSE

Action statement2

END IF;

Ex:

IF age >=18 then

Person is eligible to vote

ELSE

Not eligible to vote

(3) IF….THEN…. ELSE IF… END IF:

The statement is provided with extension to previous statement

The general syntax is

IF condition1 THEN

Action statement1

ELSEIF condition2 THEN

Action statement2

…..

ELSEIF condition N THEN

Action statement N

[ELSE

ELSE Action statements]

END IF;

Ex:IF age is >=18 THEN

The person is eligible to vote

ELSE IF <18 THEN

The person is not eligible to vote

ELSE IF wait up to age is = 18

Page 10: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Then the person is eligible to vote

END IF

(4) CASE:

The case statement is alternative to IF….THEN…. ELSE IF… END IF statement

The CASE statement begins with the key word CASE & ends with the key word END CASE

The general syntax is

CASE [variable name]

WHEN value1| condition1 THEN action_ statement1

WHEN value2| condition2 THEN action_ statement2

……

WHEN value N | condition N THEN action_ statement N

ELSE action_statement;

END CASE;

Searched case:

A statement with a value is known as a CASE statement

A statement with a condition is known as searched statement

Nested IF

The nested IF statement contains an IF statement within another IF statement

If the condition in the outer IF statement is TRUE the inner IF statement is performed

Looping structure:

Looping means interactions.

A loop repeats a statement a specific number of times as defined by the programmer

There are three types of looping statements they are:

1. Basic loop

2. WHILE loop

3. FOR loop

(1) Basic loop

The basic loop is a loop that is performed repeatedly

Once a loop is entered all statements in the loop are performed

The general syntax is

LOOP

Looping statement1;

Page 11: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Looping statement2;

…..

Looping statement N;

EXIT [WHEN condition];

END LOOP

EX: Age>=18

Age 12

Age 14

Age19

Exit

(2) While loop:

The WHILE loop is an alternative to the basic loop & is performed as long as the condition false

The general syntax is

WHILE condition LOOP

Looping statement1;

Looping statement2;

…..

Looping statement N;

END LOOP

Ex:

WHILE age is >= 18

Eligible to vote

Not eligible

END LOOP

(3) For loop

The FOR loop is the simplest loop the loop is in control variable

There is no use to use an EXIT statement

The general syntax is

FOR counter IN [reverse] lower...upper loop

Looping statement1

Looping statement2

…….

Looping statement N

END LOOP

Ex:

Page 12: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

FOR age = >=18

Person is eligible to vote

Nested loop

A loop with another loop is called as nested loop

Can be nested in many levels

Ex:

LOOP

……

EXIT WHEN condition;

LOOP

…..

EXIT WHEN condition;

LOOP

…..

EXIT WHEN condition;

END LOOP;

END LOOP;

NESTED BLOCKS:

PL/SQL may contain another PL/SQL block or it is nested

The execution starts with outer block & continues with a inner block

Ex:

DECLARE /* outer block starts here*/

Var1 NUMBER /* known to outer & inner */

BEGIN

….. /* can use var1 here*/

DECLARE /* inner block starts here*/

Var2 NUMBER /* known to inner block */

BEGIN

….. /* can use var1& var2 here*/

END; /* inner block ends here */

….

END /* outer block ends here */

Page 13: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

SQL IN PL/SQL:

The PL/SQL statements have control structures for calculations, decision making & interactions

PL/SQL supports all DML statements such as ISERT,DELETE, & UODATE

A row of data is used to assign values to variable

The PL/SQL does not support to DML such as CREATE, ALTER, & DROP

Select statement in PL/SQL:

The SELECT statement retrieves data from oracle tables

The general syntax is

SELECT columnnames; at least one column

INTO variablenames / Recordnames

FROM tablename

WHERE condition; local host variable

DATA MANIPULATION IN PL/SQL:

There are three DML statements

1. The INSERT statement

2. The DELETE statement

3. The UPDATE statement

(1) The INSERT statement

The INSERT statement to add a new statement in the table

The statement will use sequence created earlier

(2) The DELETE statement:

The use of DELETE statement in the PL/SQL block to remove some unwanted rows from the

table

(3) The UPDATE statement:

The UODATE statement can be used in a PL/SQL block for modification of data

Page 14: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

TRANSATION CONTROL STATEMENT:

The transaction control statement are capabilities in oracle

All transaction control statement are allowed in PL/SQL as

1. the COMMIT statement to commit the current transactions

2. the SAVEPOINT statements to mark a point on transactions

3. The ROLLBACK statement to discard all or part of the transactions

PL/SQL COMPOSITE DATATYPES:

RECORDS:

Records are similar in structure to a database table

A record consist of components of any scalar PL/SQL record & PL/SQL table type, these

components are called as fields & they have their own values

It enables to access the components in the group

It is based on the cursor, a table row’s or user – defined record type

It can be declare as

CURSOR cursorname IS

SECLCT query;

Recordname Cursorname%ROWTYPE;

Creating a record

To create a user – define record first type the RECORD and declare the record with RECORD

TYPE

The general syntax is

TYPE recordtypename IS RECORD

(fieldname1 datatype | variable% type | table. column % type|

table%ROWTYPE [[NOT NULL]:=|Default expression]

[fieldname 2…

fieldname 3…..);

recordname recordtypename;

Page 15: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Referencing fields in a record

A field is the record has a name that is given in the RECORD – type definition

The general syntax is

Recordname.fieldname

The recordname and the fieldname are joined by (.)

Working with records:

A record is known in the block where it is declared

When the block ends the record no longer exists

Record from the columns in a row by using the SELECT statement or the FETCH statement

A record can be set to be NULL& also all the fields are also set to be NULL

Nested records:

To create a nested record by including a record into other record as a field

The record that contains other record as a field is called the enclosing record

Ex: DECLARE

TYPE address_rectype IS RECORD

(first VARCHAR2(15),

Last VARCHAR2 (15),

TABLES:

A table is a record that composite data structure in PL/SQL

Table is single dimension structure with a collection of elements that stores the same type of

value

Declaring a table:

Declaration is done in 2 steps:

(1) Declare the table with TYPE statement

(2) Declare the actual table based on the type declare in the previous step

The general syntax is

TYPE tabletypename IS TABLE OF

Datatype | vaariablename%TYPe|tablename.columnname%TYPE

Page 16: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

[NOT NULL] INDEX BY BINARY_INTEGER;

Referencing table Elements/Rows:

The row in the table are referenced in the same way that an element in an array is referenced

The primary key value in a pair of parentheses as a subscript or index

The general syntax is

Tablename (primarykeyvalue)

Assigning values to rows in a table:

There are three ways to assign the value to rows:

(1) Direct assignment

(2) Assignment in a loop

(3) Aggregate assignment

(1) Direct assignment

Assign a value to a row within an assignment statement

There is preferable if only a few assignment are to be made

(2)Assignment in a loop

Use any of the three loop to assign values

The primary key index value will vary from 1 to 52

(3) Aggregate assignment:

The datatypes of both tables must be compatible

Assign a tables values to another table that receiving those values losses all previous primary

key values as well as its data column values

Both table must have the same type for such assignment

Built – in table method:

This method is the procedure or functions that provide informations about a PL/SQL table

The general syntax is

Tablename.methodname [(index1 [index2])]

Table of records:

It is declared with a datatype

The %ROWTYPE declaration attribute can used to define the record type

The record must consist of fields scalar data types

The record must not contain nested records

Page 17: UNIT IV PL/SQL: A PROGRAMMING LANGAUGE HISTORY

Ex:

TYPE student_record_type 19

RECORD (stu_id NUMBER (3), stu_nsme VARCHAR2 (30));

TYPE student_table_type IS TABLE OF student_record_type

INDEX BY BINARY_INTEGER

Student_table Student_table _ type;

PL/SQL VARRAYS:

A VARRAY is another composite datatype in PL/SQL

Varray stands for variable- size array

They are single- dimension, bounded collection of elements with the same data type

They retain their ordering & subscript when stored in & retrieved from a database table

Declaration:

Declare a PL/SQL VARRAY type with a TYPE statement

Declare an actual varray based on the type declared previously

The general syntax is

DECLARE

TYPE varraytypename IS VARRAY (size) OF ELEMENTType [NOT NULL]

Varrayname varraytypename