Sie sind auf Seite 1von 62

DATA TYPE IN PL/SQL

Every constant, variable, and parameter has a data type (or type), which specifies a

storage format, constraints, and valid range of values. PL/SQL provides a variety of

predefined data types. For instance, you can choose from integer, floating point,

character, Boolean, date, collection, reference, and LOB types.

1)Predefined Data types

2)User-Defined Subtypes

Predefined Data types

A scalar type has no internal components. A composite type has internal

components that can be manipulated individually. A reference type holds values, called

pointers, that designate other program items. A LOB type holds values, called lob

locators, that specify the location of large objects (graphic images for example) stored

out-of-line.

Number Types

Number types let you store numeric data (integers, real numbers, and floating-

point numbers), represent quantities, and do calculations.

BINARY_INTEGER
You use the BINARY_INTEGER data type to store signed integers. Its magnitude

range is -2**31.. 2**31. Like PLS_INTEGER values, BINARY_INTEGER values require less

storage than NUMBER values.

BINARY_INTEGER Subtypes

A base type is the data type from which a subtype is derived. A subtype

associates a base type with a constraint and so defines a subset of values.

NATURAL

NATURALN

POSITIVE

POSITIVEN

SIGNTYPE

NUMBER
NUMBER data type to store fixed-point or floating-point numbers. Its

magnitude range is 1E-130 .. 10E125. If the value of an expression falls outside this range,

you get a numeric overflow or underflow error.

The syntax follows:

NUMBER [(precision, scale)]

NUMBER Subtype:

You can use the following NUMBER subtypes for compatibility with ANSI/ISO and IBM

types or when you want a more descriptive name:

DEC

DECIMAL

DOUBLE PRECISION

FLOAT

INTEGER

INT

NUMERIC

REAL

Use the subtypes DEC, DECIMAL, and NUMERIC to declare fixed-point numbers with a

maximum precision of 38 decimal digits.


Character Types

Character types let you store alphanumeric data, represent words and text, and

manipulate character strings.

CHAR

You use the CHAR data type to store fixed-length character data. How the data is

represented internally depends on the database character set. The CHAR data type takes

an optional parameter that lets you specify a maximum size up to 32767 bytes.

The syntax follows:

CHAR [(maximum size [CHAR | BYTE] )]

CHAR Subtype

The CHAR subtype CHARACTER has the same range of values as its base type.

That is, CHARACTER is just another name for CHAR. You can use this subtype for

compatibility with ANSI/ISO and IBM types or when you want an identifier more

descriptive than CHAR.

LONG and LONG RAW


You use the LONG data type to store variable-length character strings. The

LONG data type is like the VARCHAR2 data type, except that the maximum size of a

LONG value is 32760 bytes.

You use the LONG RAW data type to store binary data or byte strings. LONG

RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL.

The maximum size of a LONG RAW value is 32760 bytes.

RAW

You use the RAW data type to store binary data or byte strings. For example, a

RAW variable might store a sequence of graphics characters or a digitized picture.The

RAW data type takes a required parameter that lets you specify a maximum size up to

32767 bytes.

The syntax follows:

RAW (maximum size)

ROWID and UROWID

Internally, every database table has a ROWID pseudo column, which stores

binary values called rowdies. Each rowed represents the storage address of a row. A
physical rowed identifies a row in an ordinary table. A logical rowed identifies a row in an

index-organized table. The ROWID data type can store only physical rowdies. However,

the UROWID (universal rowed) data type can store physical, logical, or foreign (non-

Oracle) rowdies.

VARCHAR2

You use the VARCHAR2 data type to store variable-length character data. How

the data is represented internally depends on the database character set. The VARCHAR2

data type takes a required parameter that specifies a maximum size up to 32767 bytes.

The syntax follows:

VARCHAR2 (maximum size [CHAR | BYTE])

National Character Types

The widely used one-byte ASCII and EBCDIC character sets are adequate to represent

the Roman alphabet, but some Asian languages, such as Japanese, contain thousands of

characters. These languages require two or three bytes to represent each character

NCHAR
You use the NCHAR data type to store fixed-length (blank-padded if necessary) national

character data. How the data is represented internally depends on the national character

set specified when the database was created, which might use a variable-width encoding

(UTF8) or a fixed-width encoding (AL16UTF16).

The syntax follows:

NCHAR [(maximum size)]

NVARCHAR2

You use the NVARCHAR2 data type to store variable-length Unicode character

data. How the data is represented internally depends on the national character set

specified when the database was created, which might use a variable-width encoding

(UTF8) or a fixed-width encoding (AL16UTF16).

The syntax follows:

NVARCHAR2 (maximum size)

LOB Types:

The LOB (large object) data types 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. And, they allow efficient, random, piece-wise access to the data.
BFILE

You use the BFILE data type to store large binary objects in operating

system files outside the database. The locator includes a directory alias, which specifies a

full path name (logical path names are not supported).

BFILEs are read-only, so you cannot modify them. The size of a BFILE is

system dependent but cannot exceed four gigabytes (2**32 - 1 bytes). The maximum

number of open BFILEs is set by the Oracle initialization parameter

SESSION_MAX_OPEN_FILES, which is system dependent.

BLOB

You use the BLOB data type to store large binary objects in the database, in-line or out-

of-line. Every BLOB variable stores a locator, which points to a large binary object. The

size of a BLOB cannot exceed four gigabytes.

BLOBs participate fully in transactions, are recoverable, and can be replicated. Changes

made by package DBMS_LOB can be committed or rolled back. BLOB locators can span

transactions (for reads only), but they cannot span sessions.

CLOB

You use the CLOB data type to store large blocks of character data in the database, in-

line or out-of-line. Both fixed-width and variable-width character sets are supported.
Every CLOB variable stores a locator, which points to a large block of character data. The

size of a CLOB cannot exceed four gigabytes.

NCLOB

You use the NCLOB data type to store large blocks of NCHAR data in the database, in-

line or out-of-line. Both fixed-width and variable-width character sets are supported.

Every NCLOB variable stores a locator, which points to a large block of NCHAR data. The

size of an NCLOB cannot exceed four gigabytes.

Boolean Type

BOOLEAN

You use the BOOLEAN data type to store the logical values TRUE, FALSE, and NULL

(which stands for a missing, unknown, or inapplicable value). Only logic operations are

allowed on BOOLEAN variables.


The BOOLEAN data type takes no parameters. Only the values TRUE, FALSE, and NULL

can be assigned to a BOOLEAN variable. You cannot insert the values TRUE and FALSE

into a database column.

Datetime and Interval Types

The data types in this section let you store and manipulate dates, times, and intervals

(periods of time). A variable that has a date/time data type holds values called datetimes;

a variable that has an interval data type holds values called intervals. A datetime or

interval consists of fields, which determine its value. The following list shows the valid

values for each field:

Field Name Valid Datetime Values Valid Interval Values

YEAR -4712 to 9999 (excluding year 0) Any nonzero integer

MONTH 01 to 12 0 to 11

DAY 01 to 31 (limited by the values of MONTH Any nonzero integer

and YEAR, according to the rules of the

calendar for the locale)

HOUR 00 to 23 0 to 23

MINUTE 00 to 59 0 to 59

SECOND 00 to 59.9(n), where 9(n) is the precision 0 to 59.9(n), where 9(n)


Field Name Valid Datetime Values Valid Interval Values

of time fractional seconds is the precision of

interval fractional

seconds

TIMEZONE_HOUR -12 to 14 (range accommodates daylight Not applicable

savings time changes)

TIMEZONE_MINUTE 00 to 59 Not applicable

TIMEZONE_REGION Found in the view V$TIMEZONE_NAMES. Not applicable.

TIMEZONE_ABBR Found in the view V$TIMEZONE_NAMES. Not applicable.

DATE

You use the DATE data type to store fixed-length datetimes, which include the time of

day in seconds since midnight. The date portion defaults to the first day of the current

month; the time portion defaults to midnight. The date function SYSDATE returns the

current date and time.

SELECT SYSDATE - hiredate INTO days worked FROM emp

WHERE empno = 7499;

TIMESTAMP
The data type TIMESTAMP, which extends the data type DATE, stores the year, month,

day, hour, minute, and second.

The syntax is:

TIMESTAMP [(precision)]

TIMESTAMP WITH TIME ZONE

The data type TIMESTAMP WITH TIME ZONE, which extends the data type TIMESTAMP,

includes a time-zone displacement. The time-zone displacement is the difference (in

hours and minutes) between local time and Coordinated Universal Time (UTC)--formerly

Greenwich Mean Time.

The syntax is:

TIMESTAMP [(precision)] WITH TIME ZONE


INTERVAL YEAR TO MONTH

You use the data type INTERVAL YEAR TO MONTH to store and manipulate intervals of

years and months.

The syntax is:

INTERVAL YEAR [(precision)] TO MONTH

INTERVAL DAY TO SECOND

You use the data type INTERVAL DAY TO SECOND to store and manipulate intervals of

days, hours, minutes, and seconds.

The syntax is:

INTERVAL DAY [(leading precision)] TO

SECOND [(fractional_seconds_precision)]

User-Defined Subtypes
Each PL/SQL base type specifies a set of values and a set of operations applicable to

items of that type. Subtypes specify the same set of operations as their base type but

only a subset of its values. Thus, a subtype does not introduce a new type; it merely

places an optional constraint on its base type.

For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows:

SUBTYPE CHARACTER IS CHAR;

SUBTYPE INTEGER IS NUMBER (38,0); -- allows only whole numbers


EX.NO:1 INSERTION

INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form does not specify the column names where the data will be inserted, only

their values:

INSERT INTO table name

VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:

INSERT INTO table name (column1, column2, column3)

VALUES (value1,value2,value3,);

Write a pl/sql program in insert and update in the table:

Table creation:

create table emp(eno number(3),ename char(10),depart char(10),address char(20),sal

number(6),ma number(4),hra number(4),tot number(7));

Table created.

SQL> desc emp;

Name Null? Type

----------------------------------------- -------- ----------------------------

ENO NUMBER(3)

ENAME CHAR(10)

DEPART CHAR(10)

ADDRESS CHAR(20)

SAL NUMBER(6)

MA NUMBER(4)

HRA NUMBER(4)

TOT NUMBER(7)

insert into emp values(01,'abi',,'worker','3,kk nagar',15000,


500,1000);

1 row created.

SQL> insert into emp values(02,'ram','manager','chennai',45000,20

00,3000);

1 row created.

SQL> insert into emp values(03,'prabha',`nager','mumbai',50000,

2000,4000);

1 row created.

Output:

SQL> select * from emp;

ENO ENAME DEPART ADDRESS SAL MA HRA

----- ---------- ---------- ---------- ---------- ---------- --------

1 abi worker kk nagar 15000 1000 2000

2 ram manager chennai 45000 2000 3000

3 prabha manager mumbai 50000 2000 4000

4 ammu MD georgia 20000 300 500

5 banu manager snkl 40000 900 1000

5 rows selected
SQL> declare

2 c char(10);

3 cursor e is select * from emp;

4 s e%rowtype;

5 begin

6 open e;

7 loop

8 fetch e into s;

9 exit when e%notfound;

10 if s.workingday>200 then

11 c:='good';

12 else

13 c:='satisfied';

14 end if;

15 update emp set tot=sal+ma+hra+bon,

16 con=c where eno=s.eno;

17 end loop;

18 close e;

19 end;

20 /
PL/SQL procedure successfully completed.

Output:

SQL> select * from emp;

ENO ENAME DEPART ADDRESS SAL MA HRA TOT

----- ---------- ---------- ---------- ---------- ---------- -------- -------

---

1 abi worker kk nagar 15000 1000 2000 21000

2 ram manager chennai 45000 2000 3000 55000

3 prabha manager mumbai 50000 2000 4000 61500

4 ammu manager snkl 20000 300 500 21800

5 banu manager snkl 40000 900 1000 44300

5 rows selected

EX.N0:2 FUNCTIONS

Function:
Functions can return a value to the caller, and functions can be directly referenced in

queries.

This value is returned through the use of the return keyword within the function.

Calling a Function:

While creating a function, you give a definition of what the function has to do. T o use a

function, you will have to call that function to perform the defined task. When a program

calls a function, program control is transferred to the

called function .A called function performs defined task and when its return statement is

executed or when it last end statement is reached, it returns program control back to the

main program .To call a function you simply need to pass the required parameters along

with function name and if function returns a value then you can store returned value

Syntax:

CREATE [OR REPLACE] FUNCTION function_name

[(parameter_name [IN | OUT | IN OUT] type [, ...])]

RETURN return_data type

{IS | AS}

BEGIN

< function_body >

END [function_name];

Both the header and the body of the function are created by this command.
The return keyword specifies the data type of the function’s return value. This can be any

valid PL/SQL data type (see Chapter 27). Every function must have a return clause, since

the function must, by definition, return a value to the calling environment.

Purpose:

Function_name specifies the name of the function.

[OR REPLACE] option allows modifying an existing function.

T he optional parameter list contains name, mode and types of the parameters. IN

represents that value will be passed from outside and OUT represents that this

parameter will be used to return a value outside

of the procedure.

T he function must contain a return statement.

RETURN clause specifies that data type you are going to return from the function.

function-body contains the executable part.

The AS keyword is used instead of the IS keyword for creating a standalone function.

CREATING THE TABLE:

SQL> create table bank15(accno number(3),name char(20),gender char(2),mno

number(10), addr char(20),dep number(8),bal number(8),rwith number(8));

Table created.

VIEWING THE TABLE:


SQL> desc bank15;

Name Null? Type

----------------------------------------- -------- ----------------------------

ACCNO NUMBER(3)

NAME CHAR(20)

GENDER CHAR(2)

MNO NUMBER(10)

ADDR CHAR(15)

DEP NUMBER(8)

BAL NUMBER(8)

RWITH NUMBER(8)

PROGRAM :-

SQL> create or replace function ba15(d1 in number,w1 in number)

2 return number is s number;

3 begin

4 s:=d1-w1;
5 return s;

6 end;

7 /

Function created.

SQL> declare

2 acno number(3):=&number;

3 n char(20):=&char;

4 g char(2):=&char;

5 m number(10):=&number;

6 add char(15):=&char;

7 d number(8):=&number;

8 w number(8):=&number;

9 s number;

10 begin

11 s:=ba15(d,w);

12 insert into bank15 values(acno,n,g,m,add,d,s,w);


13 end;

14 /

Enter value for number: 01

old 2: acno number(3):=&number;

new 2: acno number(3):=01;

Enter value for char: 'aruna'

old 3: n char(20):=&char;

new 3: n char(20):='aruna';

Enter value for char: 'f'

old 4: g char(2):=&char;

new 4: g char(2):='f';

Enter value for number: 200123

old 5: m number(10):=&number;

new 5: m number(10):=200123;

Enter value for char: '5 er road'

old 6: add char(15):=&char;


new 6: add char(15):='5 er road';

Enter value for number: 15000

old 7: d number(8):=&number;

new 7: d number(8):=15000;

Enter value for number: 1000

old 8: w number(8):=&number;

new 8: w number(8):=1000;

PL/SQL procedure successfully completed.

Output:

SQL> select * from bank15;

ACCNO NAME GE MNO ADDR DEP BAL RWITH

------------- ----------- ------- ---------- - ---------- ------- ------

-----------

1 aruna f 200123 5 er road 15000 14000

1000
PL/SQL procedure successfully completed.

SQL> /

Enter value for number: 3

old 2: acno number(3):=&number;

new 2: acno number(3):=3;

Enter value for char: 'balu'

old 3: n char(20):=&char;

new 3: n char(20):='balu';

Enter value for char: 'm'

old 4: g char(2):=&char;

new 4: g char(2):='m';

Enter value for number: 678456

old 5: m number(10):=&number;

new 5: m number(10):=678456;

Enter value for char: '23 ed road'


old 6: add char(15):=&char;

new 6: add char(15):='23 ed road';

Enter value for number: 12344

old 7: d number(8):=&number;

new 7: d number(8):=12344;

Enter value for number: 6788

old 8: w number(8):=&number;

new 8: w number(8):=6788;

PL/SQL procedure successfully completed.

SQL> select * from bank15;

ACCNO NAME GE MNO ADDR DEP BAL RWITH

----------- --------------- ---- --------- -------- ------ -----

----- ---------

1 aruna f 200123 5 er road 15000 14000

1000
2 divya f 213456 32 kr street 234567 222222

12345

EX.NO:3 PL/SQL CURSOR

PL/SQL uses implicit and explicit cursors. PL/SQL declare a implicit cursor for each

operation to data manipulation in SQL, including queries that returns a single

registration.

If you want precise control over the interogations, you can declare a explicit cursor;

You can define a explicit cursor for the interogations which returns more than one

registration.

1. IMPLICIT CURSOR

The implicit cursors are managed automatically by the PL/SQL, so you don't have

written any code for handling them. Can you account for the execution of a implicit

cursor through the attributes of the cursor.


2. EXPLICIT CURSOR

When you need precise control over the outcome of the interrogations, must be

declared a explicit cursor in PL/SQL.

Three commands are used to control a cursor: OPEN, FETCH and CLOSE. First time the

cursor must must be opened through the OPEN command. Then you can run FETCH

repeated until all records have been read or you can use BULK COLLECT clause to read

all recording only once. For disable/close a cursor uses the CLOSE command.

The attributes of the cursors

The attributes of the implicit cursors can return information about DML and DDL

execution commands such as INSERT, UPDATE, DELETE, SELECT INTO, COMMIT or

ROLLBACK.

The attributes are: % FOUND cursor, % ISOPEN, % NOTFOUND and %

ROWCOUNT.

% FOUND
Until SQL data manipulation is executed, the attribute % FOUND is NULL. So, %

FOUND is TRUE if the command type of INSERT, UPDATE, or DELETE affects one or more

records from the database or SELECT INTO returns one or more recordings.

% ISOPEN

Oracle closes the cursor automatically after execution of commands. As a result,%

ISOPEN becomes FALSE.

% NOTFOUND

% NOTFOUND is the opposite attribute of % FOUND.

% NOTFOUND is TRUE if the INSERT, UPDATE, or DELETE your registration does

not affect any of the database or SELECT INTO does not return any registration.

Otherwise it is FALSE.

% ROWCOUNT

% ROWCOUNT returns the number of records affected by one of the commands

that INSERT, UPDATE, or DELETE, or the number of records affected by the SELECT INTO.

% ROWCOUNT is 0 if the command INSERT, UPDATE, or DELETE does not affect any

registration, or SELECT INTO does not return any record.


Syntax

The syntax for a cursor without parameters in Oracle/PLSQL is:

CURSOR cursor_name

IS

SELECT_statement;

The syntax for a cursor with parameters in Oracle/PLSQL is:

CURSOR cursor_name (parameter_list)

IS

SELECT_statement;

The syntax for a cursor with a return clause in Oracle/PLSQL is:

CURSOR cursor_name
RETURN field%ROWTYPE

IS

SELECT_statement;

SQL> create table clg18(sno number(3), sname char(15), inter number(3), exter

number(3), tot number);

Table created.

SQL> insert into clg18 values(1,'darsini',35,50,'');

1 row created.

SQL> declare

2 total number;

3 total1 number;

4 cursor s is select * from clg18;

5 r clg18%rowtype;

6 begin

7 dbms_output.put_line('output');

8 dbms_output.put_line('student details');
9 dbms_output.put_line('NO'||' '||'NAME'||' '||'INTER'||' '||'EXTER'||' '||'TOT');

10 open s;

11 loop

12 fetch s into r;

13 exit when s%notfound;

14 total:=r.inter+r.exter;

15 total1:=r.tot;

16 total1:=total;

17 update clg18 set tot=total where sno=r.sno;

18 end loop;

19 close s;

20 end;

21 /

PL/SQL procedure successfully completed.

SQL> select * from clg18;

SNO SNAME INTER EXTER TOT


---------- --------------- ---------- ---------- ----------

1 darsini 35 50 85

2 ram 30 40 70

3 ram 32 45 77

4 sugan 40 40 80

5 sathya 37 46 83

EX.NO:4 LOOPS

You can use loops to process multiple records within a single PL/SQL block.

PL/SQL supports.

Three types of loops

Simple loops A loop that keeps repeating until an exit or exit when statement is

reached within the loop

FOR loops A loop that repeats a specified number of times.


WHILE loops A loop that repeats while a condition is met.

1) Simple Loop

A Simple Loop is used when a set of statements is to be executed at least once

before the loop terminates.

An EXIT condition must be specified in the loop, otherwise the loop will get into an

infinite number of iterations. When the EXIT condition is satisfied the process exits from

the loop.

Syntax:

LOOP

statements;

EXIT;

{or EXIT WHEN condition;}

END LOOP;

These are the important steps to be followed while using Simple Loop.

1) Initialize a variable before the loop body.

2) Increment the variable in the loop.


3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement

without

4) WHEN condition, the statements in the loop is executed only once.

Example:

DECLARE

VAR1 NUMBER;

VAR2 NUMBER;

BEGIN

VAR1:=100;

VAR2:=1;

LOOP

DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);

IF (VAR2=10) THEN

EXIT;

END IF;

VAR2:=VAR2+1;
END LOOP;

END;

Sample Output:

100

..

1000

2) FOR Loop:

A 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 reachs the value of the end

integer.

Syntax:

FOR counter IN val1..val2

LOOP statements;

END LOOP;
val1 - Start integer value

val2 - End integer value

Example:

DECLARE

VAR1 NUMBER;

BEGIN

VAR1:=10;

FOR VAR2 IN 1..10

LOOP

DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);

END LOOP;

END;

Sample Output:

10

..

100.
3) While Loop

A WHILE LOOP is used when a set of statements has to be executed as long as a

condition is true. The condition is evaluated at the beginning of each iteration. The

iteration continues until the condition becomes false.

Syntax:

WHILE <condition>

LOOP statements;

END LOOP;

Example:

DECLARE

VAR1 NUMBER;

VAR2 NUMBER;

BEGIN

VAR1:=200;

VAR2:=1;
WHILE (VAR2<=10)

LOOP

DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);

VAR2:=VAR2+1;

END LOOP;

END;

Sample Output:

200

400

600

700

1000

1200

1400

1600

1800
2000.

4) Simple Cursor Loops:

Cursor:

Cursor is a temporary memory area (context area) where Oracle executes SQL

statements. Oracle associates every SELECT statement with a cursor to hold the query

information in this context area.

Types of Cursor

There are two types of cursors - implicit and explicit cursor.

Implicit cursor

Oracle automatically (implicit) controls or processes the information of SQL

statement executed. In this process, the user is unaware of implicit cursor. Oracle

automatically performs the OPEN, FETCH, and CLOSE operations.

Explicit cursor

Explicit cursor is used for the query that returns more than one row of data. These

cursors are explicitly declared in the DECLARE section of the PL/SQL block. This

declaration allows to sequentially process each row of data as the cursor returns it. In
explicit cursor DECLARE, OPEN, FETCH, and CLOSE operations are done by the

programmer.

The process of working with an explicit cursor

Declare: The cursor is initialized into temporary memory area.

Open : The cursor is opened which is declared, and the temporary memory area is

allotted.

Fetch : Cursor which is declared and opened can now retrieve rows from data.

Close : The CLOSE statement disables the cursor, and releases the temporary memory

area.

Cursor Attributes

These attributes return useful information about the execution of a SQL statement.

Syntax for creating a cursor

CURSOR cursor_name IS select_statement;

CURSOR ATTRIBUTE SYNTAX DESCRIPTION


%NOTFOUND cursor_name%NOTFOUND %NOTFOUND

returns TRUE if last fetch did not return a row, Else FALSE. If last fetch returns row.

%FOUND cursor_name%FOUND %FOUND returns

TRUE if the cursor is open, fetches the row till the last fetches FALSE if last

fetch did not return any row

%ROWCOUNT cursor_name%ROWCOUNT %ROWCOUNT keeps

track of fetched rows from cursor until it is closed

%ISOPEN cursor_name%ISOPEN %ISOPEN returns

TRUE if its cursor orcursor variable is

open,otherwise, %ISOPEN returns FALSE.

EXAMPLE

DECLARE

CURSOR T IS SELECT * FROM ST;

S T%ROWTYPE

BEGIN

OPEN T
LOOP

FETCH T INTO ST

EXIT WHEN T %NOTFOUND

UPDATE ST SET TOTAL:=S.M1+S.m2 WHERE RNO:=S.RNO;

END LOOP;

CLOSE T;

END;

OUTPUT

SELECT * FROM STUD;

RNO NAME M1 M2 TOTAL

1 RAJA 89 98 187

2 RAJU 94 96 191
EX.NO:5 PROCEDURE

A procedure is a group of SQL and PL/SQL commands that execute certain

tasks. In a database management system , a procedure is a set of Structured Query

Language (SQL) statements with an assigned name that's stored in the database in

compiled form so that it can be shared by a number of programs. The use of stored

procedures can be helpful in controlling access to data,preserving data integrity

(information is entered in a consistent manner), and improving productivity (statements

in a stored procedure only need to be written one time).

SYNTAX :

The syntax to create a procedure in Oracle is:


CREATE [OR REPLACE] PROCEDURE procedure_name

[ (parameter [,parameter]) ]

IS

[declaration_section]

BEGIN

executable_section

[EXCEPTION

exception_section]

END [procedure_name];

When you create a procedure or function, you may define parameters. There are three

types of parameters that can be declared:

1. IN - The parameter can be referenced by the procedure or function. The value of

the parameter can not be overwritten by the procedure or function.

2. OUT - The parameter can not be referenced by the procedure or function, but the

value of the parameter can be overwritten by the procedure or function.


3. IN OUT - The parameter can be referenced by the procedure or function and the

value of the parameter can be overwritten by the procedure or function.

AIM :

To perform procedure to prepare an electricity bill.

CREATING A PROCEDURE :

create or replace procedure prnam(cur number,pre1 number)

as

nunit number;

amt number;

begin

nunit :=cur-pre1;

update eb set unit=nunit where pre=pre1;

if (nunit <300)

then

update eb set amount=nunit*1.3 where pre=pre1;


end if;

if(nunit >=300)

then

update eb set amount=nunit*1.6 where pre=pre1;

end if;

end prnam;

RUN THE PROCEDURE:

SQL> set serveroutput on;

SQL> start promaneb;

Procedure created.

CALLING PROCEDURE :

declare

cursor c is select * from eb;

cv c%rowtype;
begin

open c;

loop

fetch c into cv;

exit when c%notfound;

prnam (cv.cur,cv.pre);

end loop;

close c;

end;

RUN THE CALLING PROCEDURE :

SQL> set serveroutput on;

SQL> start promanebcall;

PL/SQL procedure successfully completed.


ANOTHER WAY :

CREATING A PROCEDURE :

create or replace procedure nampr

as

begin

update eb set unit=cur-pre;

update eb set amount=(cur-pre)*1.4;

end;

RUN THE PROCEDURE :

SQL> set serveroutput on

SQL> start ebcp;

Procedure created.

USING EXEC COMMAND :


From sql*plus a procedure can be called with the EXECUTE command.

SQL> exec nampr;

PL/SQL procedure successfully completed.

OUTPUT :

SQL> select * from eb;

NO NAME CUR PRE UNIT AMOUNT

---------- -------------- ---------- ---------- ---------- ----------------

211 sasa 1500 890 610 976

234 mano 980 780 200 260

324 ze 1200 900 300 480

455 raj 899 679 220 286

500 beena 2000 1450 550 880


EX.NO:6 TRIGGER

A trigger is a pl/sql block structure which is fired when a DML statements like Insert,

Delete, Update is executed on a database table. A trigger is triggered automatically when

an associated DML statement is executed .Oracle engine invokes automatically whenever

a specified event occurs .A trigger is a special kind of a store procedure. You can’t

explicitly invoke striggers Trigger is stored into database and invoked repeatedly, when

specific condition match

Component of Trigger

Triggering SQL statement : SQL DML (INSERT, UPDATE and DELETE) statement that

execute and implicitly called trigger to execute.

Trigger Action : When the triggering SQL statement is execute, trigger automatically call

and PL/SQL trigger block execute.

Trigger Restriction : We can specify the condition inside trigger to when trigger is fire.
Type of Triggers

1. BEFORE Trigger :

BEFORE trigger execute before the triggering DML statement (INSERT, UPDATE,

DELETE) execute. Triggering SQL statement is may or may not execute, depending on

the BEFORE trigger conditions block.

2. AFTER Trigger :

AFTER trigger execute after the triggering DML statement (INSERT, UPDATE,

DELETE) executed. Triggering SQL statement is execute as soon as followed by the

code of trigger before performing Database operation.

3. ROW Trigger :

ROW trigger fire for each and every record which are performing INSERT, UPDATE,

DELETE from the database table. If row deleting is define as trigger event, when

trigger file, deletes the five rows each times from the table.

4. Statement Trigger :

Statement trigger fire only once for each statement. If row deleting is define as

trigger event, when trigger file, deletes the five rows at once from the table.

5. Combination Trigger :
Combination trigger are combination of two trigger type,

1. Before Statement Trigger : Trigger fire only once for each statement before

the triggering DML statement.

2. Before Row Trigger : Trigger fire for each and every record before the

triggering DML statement.

3. After Statement Trigger : Trigger fire only once for each statement after the

triggering DML statement executing.

4. After Row Trigger : Trigger fire for each and every record after the

triggering DML statement executing.

PL/SQL Triggers Syntax

PL/SQL trigger define using CREATE TRIGGER statement.

CREATE[OR REPLACE]TRIGGER trigger_name

BEFORE |AFTER

[INSERT,UPDATE,DELETE[COLUMN NAME..]

ON table_name

Referencing [ OLD AS OLD | NEW AS NEW ]

FOR EACH ROW|FOR EACH STATEMENT [WHEN Condition ]


DECLARE

[declaration_section

variable declarations;

constant declarations;

BEGIN

[executable_section

PL/SQL execute/subprogram body

EXCEPTION

[exception_section

PL/SQL Exception block

END;

AFTER TRIGGER:
This trigger fires after SQL Server completes the execution of the action successfully that

fired it.

SYNTAX:

CREATE [ OR REPLACE ] TRIGGER trigger_name

AFTER INSERT ON table_name[ FOR EACH ROW ]

DECLARE

-- variable declarations

BEGIN

-- trigger code

EXCEPTION

WHEN ...

-- exception handling

END;

EXAMPLE:

CREATE OR REPLACE TRIGGER trigger_test_ar_trg

AFTER INSERT OR UPDATE OR DELETE ON trigger_test

FOR EACH ROW

BEGIN

trigger_test_api.g_tab.extend;
CASE

WHEN INSERTING THEN

trigger_test_api.g_tab(trigger_test_api.g_tab.last) := 'AFTER EACH ROW INSERT

(new.id=' || :new.id || ')';

WHEN UPDATING THEN

trigger_test_api.g_tab(trigger_test_api.g_tab.last) := 'AFTER EACH ROW UPDATE

(new.id=' || :new.id || ' old.id=' || :old.id || ')';

WHEN DELETING THEN

trigger_test_api.g_tab(trigger_test_api.g_tab.last) := 'AFTER EACH ROW DELETE

(old.id=' || :old.id || ')';

END CASE;

RAISE_APPLICATION_ERROR(-20000, 'Forcing an error.');

END trigger_test_ar_trg;

Trigger created.

OUTPUT :
SQL>SET SERVEROUTPUT ON

SQL>INSERT INTO trigger_test VALUES (1, 'ONE');

ERROR at line 1:

ORA-20000: Forcing an error.

ORA-06512: at "TEST.TRIGGER_TEST_AR_TRG", line 11

ORA-04088: error during execution of trigger 'TEST.TRIGGER_TEST_AR_TRG'

BEFORE TRIGGER:

BEFORE trigger execute before the triggering DML statement (INSERT, UPDATE,

DELETE) execute. Triggering SQL statement is may or may not execute, depending on

the BEFORE trigger conditions block

SYNTAX:

CREATE [ OR REPLACE ] TRIGGER trigger_name

BEFORE INSERT ON table_name[ FOR EACH ROW ]

DECLARE

variable declarations

BEGIN
trigger code

EXCEPTION

WHEN ...

exception handling

END;.

EXAMPLE:

create or replace trigger display_salary_changes

before delete or insert or update on customers

for each row

when (NEW.ID > 0)

declare

sal_diff number;

begin

sal_diff :=:NEW.salary - :OLD.salary;

dbms_output.put_line('old salary: '|| :OLD.salary);


dbms_output.put_line('new salary: '|| :NEW.salary);

dbms_output.put_line('salary difference: ' || sal_diff);

end;

Trigger created.

OUTPUT:

Sql> insert into customers values(7,’krish’,22,’hp’,9500.00);

1 row created.

Sql> update customers set salary=salary+500 where id=2;

1 row updated.

Sql> select * from customers;

Id name age address

salary

1 madhu 19 20,anna nager

12000
2 sangee 20 42,south street

12,500

3 varal 19 20,mk street

11,500

7 krish 22 20,hp street

9,500

Das könnte Ihnen auch gefallen