Anda di halaman 1dari 23

INDEX

Sr. No TOPIC Pg. No


1. Introduction of Oracle 3
2. SQL 3
3. Rules for SQL 4
4. Component of SQL 4
5. DDL (Data definition Language) 4
6. DML (Data Manipulation Language) 4
7. DQL (Data Query Language) 4
8. DCL (Data Control Language) 5
9. Basic Data type of Oracle 5
10. Creation of table/Create Table Command 5
11. Desc Table 6
12. Insert 6
13. Alter table 6
14. Update command 7
15. Select 7
16. Sorting data in a table 8
17. Delete the record 8
18. Truncate table 9
19. Group by clause 9
20. Having clause 9
21. Oracle function 10
22. Some oracle functions 10
23. Data constraints 11
24. I/O constraints 11
25. Primary key constraints 11
26. Foreign key constraints 11
27. Check constraints 12
28. Join 12
29. Types of joining 12
30. Self join 12
31. Union join 12
32. Minus clause 12
33. Sub-queries 13
34. Security management 13
35. Granting and revoking permission 13
36. Granting privileges 13
37. Revoking privileges 13
38. Indexing 14
39. View 14
40. What is PL/SQL and their advantages 15
41. Block of PL/SQL 15
42. Displaying messages on VDU screen 15
43. Constants 16
1
44. Variable 16
45. Iterative control 17
46. LOOP…END LOOP 18
47. WHILE…END LOOP 18
48. FOR…END LOOP 19
49. Goto Statement 19
50. PL/SQL transaction 20
51. Commit 20
52. Roll back 20
53. Save point 20
54. Cursor 20
55. Trigger 21
56. Types of trigger 21
57. Row trigger 21
58. Statement trigger 21
59. Error handling in PL/SQL 21
60. Normalization 22

2
Introduction of Oracle
In June 1970 Dr. E.F CODD publish a paper in title a relationship model of data. For large share data banks this relational
model sponsored by IBM then come too accepted as the defined model RDBMS. The language developed by IBM to maintain
data store with in CODD‟s model was originally called SEQEL (Structured English Query Language). In 1979 a company
called relational software incorporation release the first commercially available implementation of SQL. The relational
software and this is later comes to known as oracle corporation. The oracle corporation company produce the most widely use
best multi user RDBMS named oracle.

The oracle database is an object relational database management system in which we found some
following software development tools of oracle:-

i. SQL
ii. SQL *PLUS
iii. SQL/PL-SQL
iv. FORMS
v. REPORTS
vi. MENU
vii. GRAPHICS
viii. IDS
ix. EXP
x. IMO
xi. ORATERM
xii. SQK *LOADER
xiii. SQL *DBA/SBR MGR/OEM
xiv. ORACLE CASE
xv. DESIGNER 2000
xvi. ORACLE POWER OBJECT
xvii. OLE
xviii. ORACLE MANUFACTURING
xix. ORACLE HRMS(*human resource)
xx. ORACLE APPLICATION
xxi. ORACLE CRM
xxii. ORACLE WEB BROWSER
xxiii. DISCOVER 2000
xxiv. PERSONAL ORACLE
xxv. DEVELOPER 2000

SQL (Structured Query Language):-

SQL is a special purpose domain specific language used in programming and


design for managing data held in a relational RDBMS. It is a language that provides an interface to relational database system.
It was developed by IBM based upon relational algebra and to open relational calculus. The SQL consist of DDL, DML and
DCL. The scope of SQL includes insert, query, update, delete, schema creation, modification and data access control. The
3
SQL was one of the first commercial language of Dr. E.F CODD. It was initially developed at IBM Donald D Chamberian
and Romand F. Boyee. We found the following features of SQL.

i. SQL can be used by a range of user including DOS with little or no programming experience.
ii. It is non-procedural language.
iii. It reduces the amount of time used for creating and manipulating system.
iv. It is English like language.

Rules for SQL:-

i. The SQL start a verb. This verb may have additional adjective. E.g. select from, insert into.
ii. Each verb formed by a number of classes. E.g. from, where, having.
iii. Space separates a clause.
iv. A comma (,) separate parameter into a clause.
v. A semi column (;) is used to end a SQL statement.
vi. Statement may be split across the line but keyword may not.
vii. Identifier may contain 30 characters and must be start with a alphabetical character.
viii. Character or date must be enclosed in a single quote.
ix. Logical unit such as identifiers, operator name literal are separated by one or more space or other parameter that will
not confuses with logical unit.
x. Comment may be - - for single line and enclosed with */------*/ for multi line.

Component of SQL:-

We know that the SQL is a part of database creation and data manipulation and also perform data
controlling work and most important data query work. We found some following components of SQL according to their
nature of work:-

i. DDL (Data Definition Language):-

It is a set of SQL commands used to create, modify and delete the database structure. These commands are
normally not used by general user, used by DBA. In this we found the following commands:-

a. CREATE: - This command helps to create new table, index, view, cursor and etc.
b. ALTER: - This command helps to perform modification in double structure, view and etc.
c. DROP: - It helps to remove table, index, and view cursor etc.
d. TRUNCATE: - It helps to remove entire table.
ii. DML( Data Manipulation Language):-

It is the area of SQL that allow us to change data within the database. this type of command generally used by
general users. Insert, update, delete these are the examples of DML.

a. INSERT: - It is used to insert a new row (records) in the existing table.


b. UPDATE: - By using this command, we can update the information of particular record or entire records of the table.
c. DELETE: - Delete the specific row of the table.
iii. DQL(Data Query Language):-

It is the component of SQL statement that allows getting data from database and imposing ordering upon it. It
includes the select statement. This command is the heart of the SQL. It allows getting the data out of the database and

4
performs operation with it. When a select is fired against a table or the result is compiled into further in temporarily table
which is displayed of phrase received by the program.

iv. DCL(Data Control Language):-

It is the component of SQL that control access to data and to the database. Occasionally DCL command grouped
with DML command.

a. COMMIT: - It closes the transaction and save the table.


b. SAVE POINT: - Define a logical name of data transactions on table like a bookmark.
c. GRAND: - This command is used to give the permission to the other user for data handling in your database.
d. REVOKE: - Remove granted permission on a database which is given by a new user.

BASIC DATA TYPES OF ORACLE.


Data type comes in several form and size allowing the programmer to create table suited to the scope of
project. The decision made in the choosing proper data type, Influences of the performance of a database. Oracle supports
some following data types:-

i. Char (Size):- This data type is used to store character string value of fixed length. The size in the bracket determines
the number of character the shell can hold. Its maximum length is 255 characters.
ii. Varchar2 (Size):- This data type is used to store variable name, alphanumeric variables. It is more flexible than char
data type. Its maximum length is 4000 character.
iii. Date: - This data type is used to date and time. The standard format is DD-MON-YY. Here, the valid date range is 1st
January 4712 to 31st December 9712 AD.
iv. Number (p, s): - The number data type is used to store a number. Numbers of virtually any magnitude may be store up
to 38 digit of precision.
v. Long:- This data type is used to store variable name, string length contain up to 2GB. Long data can be used to store
array of binary data in ASCII formations.
vi. Raw/Long Raw:- This type of variable is used to store binary data such as digitize picture or image.

CREATION OF TABLE/ CREATE TABLE COMMAND.

For creation of a new table, we have to use create table command. The create table command defines each column of the table
uniquely. Each column has a three attributes. Name, data type and size each column definition is a string clause in the create
table.

Each column definition is separated by comma and the end of the statement we use semi-column. We know that
in the RDBMS we can store data in the form of table for this in SQL we use create table command. It is an example of DDL
command. It always helps to create a new table.

Syntax:-

Create table tablename (column1name datatype (size)……… columnnname (datatype (size)) ;

Ex:-

Create table list (name varchar2[5],roll number[5]));

5
DESC table:-

This command helps to see the structure of the table. It is also an example of DDL command.

Syntax:-

DESC table tablename;

Example:-

DESC table employee;

INSERT:-

It is an example of DML command, by using this we can add more and more records/row in a table one by one.
By using this command we can add specific information in one row/record or entire information of one record. With this
command we always use into clause with table name where we want to add record/rows. For specific column value, here we
define column name but if we want to add all information in entire column of one row then not need to define columns name.
With this command we also use values clause for giving new information. With values clause we define different column
information according to their data types separated by comma. All information are inside in bracket and at the last of this
command we use a semi-column for terminating.

Syntax:-

a. INSERT into tablename values(information1,information2……);

The above syntax is used to insert entire column value of row.

b. Insert into tablename (column1, column2….) values( information1,information2….);

The above syntax is used to insert information in specific column not entire columns.

c. Insert into tablename select column1, column2 from table2;

By using the above syntax, we can insert some specific column value from another table‟s columns.

ALTER TABLE:-

Once a table is created we can also modify the structure of the table as a modification we can add a new
field/ columns in table or increase or decrease the size of change the data type of specific columns from table. For doing this
in SQL we use alter table command. The alter table command is an example of DDL command. By using this we can perform
modification in table structure. As a modification we can do three things:-

i. Add a new file:-

Here, we can add a new column/field in table. For this we use the following syntax

Syntax:- Alter table tablename ADD(fieldname datatype( size));

Ex:- Alter table employee ADD(B_Salary number(10,2));

ii. Perform modification in existing column:-

6
Here, we can increase or decrease the length of any specific columns/fields or change the data
type of specific columns. For this we use the following syntax.

Syntax:- Alter table tablename MODIFY(fieldname data type(size));

Ex:- Alter table employee MODIFY(B_SALARY number(15,5));

iii. Remove specific field:-

Here, we can remove any existing column/field from the existing table.

Syntax: - Alter table tablename DROP (columns name);

NOTE: - we can remove only those columns which is fully empty.

UPDATE COMMAND:-

In SQL, once a row is inserted in table, we can also modify it. Here, we can change column value of
specific row or entire row and for this work here we use UPDATE command. The update command is an example of DML
command. In record manipulation work we can change the value of columns.

SYNTAX:- UPDATE tablename SET columnname= EXPRESSION

By using the above syntax, we can change the value of entire columns.

EX:- UPDATE exam SET total=P1+P2+P3;

Update student set remarks= “pass” where p1>=40 AND p2>=40 AND p3>=40;

Update student set remarks= “fail” where p1<=40 OR p2<=40 OR p3<=40;

SELECT:- Once a table is created, we insert data into table. The next most logical operation would be to view what has been
inserted. In SQL we use select verb to view data of table. It is an example of DQL. The select command is used to retrieve
selected row from one or more table. We use many time SQL command with different-different adjective and clauses. Here,
we use many clauses with select command. The SQL is totally based on its different clauses are used with select command is
make SQL. The SELECT command is also known as the heart of SQL which may very important role in view data on the
database.

Syntax:-

i. select * from tablename;

By using the above syntax we can see/retrieve all row of specific table.

ii. select column1, column2……. From tablename;

This command show selected fields from entire row.

iii. Select * from tablename where <conditions>;

This command helps us to retrieve specific record which fulfills the given condition.

7
Some other clauses that are used with Select command are as follows::

i. BETWEEN:- Thus clause is used for numeric expression/value. Where, we define two value minimum and
maximum than it will be show the value that range is between from minimum and maximum.

Syntax:- select * from tablename where columnname between (min, max);

Ex:- select *from exam where percent between( 60,80);

ii. IN:- we use this clause for defining a specific value.

Syntax:- select * from tablename where fieldname in(value1, value2,… valuen);

Ex:- select * from exam where roll in (25,30,32,21);

iii. LIKE:- we use this for text expression for finding out any specific.

Syntax:-

a). select * from tablename where column like „%c‟;

Ex:- select * from exam where name like „%A‟;

Show those records only which anme in foumd „A‟ letter.

b). select *from exam where name like „_A%‟;

shows those records only in which A letter is found in second position in name field.

Sorting data in a table:-

Oracle allows data from a table to be viewed in a sorted order. The rows retrieved from the table will be
sorted in either ascending or descending order depending on the conditions specified in the select statement.

SYNTAX:-

Select range from tablename order by colum1, column2 sort order;

By default, it will perform sorting on ascending order. For descending order sorting we must use DESC
clause at last in above syntax.

EXAMPLE:-

Select *from result order by roll_no;

The above statement arranges students record in roll wise ascending order.

Select *from result order by per desc;

The above statement arranges all students‟ records in descending order using their percentage of marks.

Delete the record:-

In SQL, the verb delete is used to remove a set of row or all rows of table. It is an example of DML.

8
Syntax:-

Delete from tablename;

Using this syntax, we can delete entire row of table.

Delete from tablename where conditions.

This syntax is also used for remove some set of row which fulfills your given conditions.

Truncate Table:-

It is also an example of DML command which is used to remove entire set of records from the table at once,
it means empty the table.

Syntax:-

Truncate table tablename;

Drop table:-

This is an example of DDL command used to destroy the table that means remove table from the database

Syntax:-

Drop table tablename;

Group by clause:-

The group by clause is another section of select statement. This clause tells oracle to group row based on distinct values that
exist for specifies columns. The group by clause create a data set containing several sets of record grouped together based on
a condition.

Syntax: range from table where conditions group by expression;

Ex: select B_SALARY from employee group by grade;

: select avg(B_SALARY)from employee group by gender;

: select count(gender)from employee group by grade;

Having clause:-

The having clause is a conjunction used with group by clause. Having impose a condition on the group by clause which
further filters the group created by the group by clause.

Ex: select avg(B_SALARY) from employee group by gender having gender=‟M‟;

: select count(gender) from employee group by grade having grade=‟A‟;

9
Oracle Functions:-
The Oracle function serves the purpose of manipulating data item and retrieving a result. Functions are
also capable of accepting user supplied variable or constants and operate on them. Such variable or constant are called
ARGUMENTS. Any number of arguments or no argument is depends on function.

Oracle functions can be clubbed together depending upon whether they


operate on a single row or a group of row retrieved from a table. According to this, functions can be classified as two types:-

 Group Function
 Scalar Function

 Group function: - The function that act on a set value are called group function. Sum, max, min, avg etc are the example
of Group Function.

Scalar Function:- A functions that act on only one value at a time are called scalar function. Length, string related
functions are the example of Scalar function.

Functions can be classified corresponding to different data type link as follows:-

 String ( ):- It work on string data type functions.


 Numeric ( ):- It work on numeric data type functions.
 Date ( ):- It work on date data type functions.
 Conversion ( ):- It work on conversion of any data type to another data type.

Some Oracle functions:-

 Avg ( ):- This function returns avg. value of „n‟ ignoring null value in a column.

Ex:- select Avg. (B_SALARY) “Avg. basic Salary” from employee;


This statement shows the average of B_SALARY field.

 Max( ):- It is an example of scalar ( ) returns a maximum value of expression .

Ex:- Select max(B_SALARY) in employee;

 Min ( ):- It is an example of scalar ( ) returns a minimum value of expression.

Ex:- Select min(B_SALARY) in employee;

 Count ( ):- This function returns the number of row in a table. In this counting including duplicate and
also nulls.

Ex:- Select count(*) “total no. of records” from employee;

 Sum ( ):- ex:- sum (HRA) „total hra” from employee;


 Lower ( ):- Return character with all letters in lower case. It is an example of Scalar function.
10
Ex:- select lower(Emp_Name) from employee; [ALL EX. SAME]

 Upper( ):- Return character with all letters in upper case. It is an example of scalar function.
 Initcap( ):- Return character with all letter in proper case. It is an example of scalar().

Data Constraints
In business world, business manager determine a set of business rules that must be applied to the data prior being sorted in the
database/table. It ensures its integrity. The business rule which is enforced on data being stored in a table called Constraint.
Constraints super control the data being entered into a table for permanent storage. The Oracle permits data constraints to be
attached to the table column via SQL syntax. That checks out data for entry. Once data constraints are the part of a table
column construct the Oracle engine checks the data being entered into a table column against the data constraints. If the data
pass this check, it is stored in the table else the data is rejected using the create table and alter table SQL command we ca n
attach constraints in the table column.

These are two types of data constraints that can be applied to the data being
inserted into Oracle table.

i. I/O constraints
ii. Business rule constraints.
i. I/O constraints:-

This data constraint determines the speed at which data can be inserted or extracted from table. This data
constraint further divided into two constraints:-

a. Primary key constraints:-

The primary key constraints attach to a table column. Then ensure that the data entered in the
table column is unique across the entire column and it also ensure that the cell belonging to the table column or left empty.
The primary key is one or more columns. In a table it is used to uniquely identify each row in a table. A single primary key is
called a simple key and multi column primary key is called composite primary key.

SYNTAX:- Columnname datatype (size) primary key;

Using the above syntax, we can define the primary key as column label constrants
and using this, we can define only simple primary key. For defining a composite primary key we use table label.

SYNTAX:- primary key(col1,col2);

Emp_code number(10,3) primary key;

b. Foreign key constraints:-

This is the another type of I/O constraints. The foreign key represents relationship between tables.
A foreign key is a column or group of columns whose values are derived from the primary key or unique key of some other
table.

11
The table in which the foreign key is defined is called foreign table or detail table and the table that defines the
primary or unique key and referenced by foreign key is called primary table or master table. The master table can be
referenced in the foreign key using the following clauses.

SYNTAX:-

References tablename.columnname

Ex:-

create table trans(ac_no number(5) references master(ac_no));

check constraints:-

This is an example of business rules constraints. Business rule validation can be applied to a table column
using check constraints. The check constraints must be specified as a logical expression that evaluate either „TRUE‟ or
„FALSE‟.

SYNTAX:-

Columnname datatype (size) check (logical expression);

Ex:-

Age number(2) check(age between 18 and 60));

JOINS:-
Sometime it is necessary to work with multiple table as tables. They were a single entity then a single SQL
sentences can manipulate data from all the tables and for this here we use join process. Join is a procedure to connect more
than one table. Tables are joined on columns that have the same data type and data width in the table that means for joining
two tables must have a same columns.

Ex:-

1. Select mode, date, amount from trans, master where master.ac_no = trans.ac_no order by mode;
2. Select name, ac_no, balance, mode, amount from master, trans where master.ac_no = trans.ac_no order by(date);

Type of joining:-

i. Self join: - In some situation, it is necessary to join a table to itself as though joining two separate tables and this is
referred as self join. Here two rows from the self table combined to form a result row.

To join a table to it, two copies of the same table have to be open in memory using the
from clause the table name need to be mentioned twice.

ii. Union join: - The multiple queries can be put together and their output can be combined using the union clause. The
union clause merges the output of two or more queries into a single set of row and column.

Ex:- select ac_no, name union select ac_no, amount, mode from trans;

12
iii. Minus clause: - multiple queries can be put together and their output combined using the minus clause. The minus
clause output the rows produced by the first query after filtering the rows retrieved by the second query.

Ex: - select ac_no from master minus select ac_no from trans;

Sub-queries:-

A sub-query is a form of an SQL statement that appears inside another SQL statement. It is also termed as
Nested Query. The statement containing a sub query is called parent statement. The parent statement uses the row return by
the sub query.

Ex:- Select * from master where ac_no=(select ac_no from trans where mode= „D‟);

Security management
Granting and Revoking permission:-

Oracle provides extensive security feature in order to safe guard information stored in its
table from unauthorized viewing and damaging. Depending upon a user‟s status and responsibility appropriate rights on
oracle resources can be assigned to the user by DBA. The rights that allow the use of some or all of oracles resources on the
server are called privileges. In oracle, user wishes to access the object of another user. The owner of the object will have to
give permission for such access and this is called granting of privileges. The privileges once given can be taken back by the
owner of objects and this is called revoking of privileges.

Granting privileges:-

The granting means allowing the access of the objects from the owner of the object to another user and
we can do this by using the grant statement. The grant statement provides various type of access to database such as table,
view, sequence and so on.

Syntax:- Grant objectprivileges on objectname to username;

User can give alter, delete, index, insert, select, update or all access rights.

Ex:- Grant select, alter on master to monu;

Permission/privileges:-

1. Alter:- It changes the table definition using alter table command.


2. Delete:- It remove the records from the table using delete command.
3. Insert:- It inserts or add new record in table.
4. Select:- It is used for query work.
5. Update:- It is used to modify the records in table.
6. With grant option:- Allow the guarantee to turn grant object privileges to another user.

Revoking privileges:- Privileges once given can be denied to a user using revoke command. The object owner can revoke
privileges guaranteed to another user.

Syntax:- Revoke objectprivileges on objectname to username;

13
Indexing:-

It is a process to create an index file where records are arranged in ascending or descending order using one or
more than one. In oracle, indexing a table is an access strategy that is a way to sort and search records in the table. Indexes
are essential to improve the speed with records can located and retrieved from the table.

Syntax:- Create index indexname on tablename (columnname);

The above syntax is of simple index where using one column we can create
indexes. Here, we can also use more than one column for indexing and that type of index is called composite index.

Syntax:- Ascending order

Create index indexname on tablename(column1,column2……);

Ex:- Create index R1 on result(grade,percentage);

By default indexes work action on ascending order, for descending order we use reverse
clause.

Syntax:- Descending order

Create index indexname on tablename(columnname) reverse;

After indexing here, we create an index file which can be modified using the Alter
index statement.

Once, we create an index file we can also delete using the drop index statement.

VIEW:-

After a table is created and populated with data, it may become necessary to prevent all columns of data for data security
reason. This would means creating several tables having the appropriate no. of columns and assigning specific users to each
table as required for this oracle allow the creation of object that is called view. A view is mapped to the select sentences the
table on which the view is based is described in from clause of select statement. We create a view for following reason:-

i. When data security is required.


ii. When data redundancy is to be kept to the minimum while maintaining data security.

A view is mapped to a table and subset of the actual column of


the table from which it is view. This technique offers a simple, effective way of hiding columns of a table.

Syntax:- create view viewname as select (columnsname……) from tablename criteria;

Ex:- create view detail as select (name, ac_no, add, DOB, mob, ac_type, cus_Id) from master;

Select *from detail;

Drop view viewname:- using this we can remove view.

Syntax:- Drop view viewname;

14
PL/SQL (Procedural Language/Structured Query Language)

Q. What are PL/SQL and their advantages?

The PL/SQL is a procedural language means procedural language and extension of SQL. It is the product of Oracle
Corporation which is included in the oracle 6.0. The PL/SQL includes procedural language elements such as
conditions and loops. It allows declaration of constants and variables and procedure functions trigger and etc. It can
handle exceptions also. Arrays are supported involving the use of PL/SQL collections. We found some following
advantages of PL/SQL are:-
i. The PL/SQL is the development tool that support SQL data manipulations and database programming also.
ii. The PL/SQL also permits dealing with errors as required and facilities to display user friendly messages when
errors are encountered.
iii. Here you can work with variable that can be used to store intermediate results for increasing for later process
and calculate value and insert them into oracle table. PL/SQL variable can be used anywhere in program.
iv. The PL/SQL block turn reduce the network traffic and improves the performance time of oracle engine
because PL/SQL block sends the entire block of statement to the oracle engine at a time.
v. It improves the transaction performance because without the use of oracle engine all sorts of calculations can
be turned quickly and efficiently.
vi. The application written in PL/SQL is portable to any computer hardware and operating system, where oracle
is operational. The PL/SQL code blocks written for DOS and UNIX also.
The PL/SQL is a block of structured programming language that enables
developer to combine the power of SQL with procedural statements and removes the disadvantage of SQL. The
PL/SQL bridges the gap between database technology and procedural programming language.

Block of PL/SQL
In every programming environment allows the creation of structured logical blocks of code that describes
process. The PL/SQL also permits the creation of structured logical blocks of code that describe processes which have
to be applied to the data. A single PL/SQL code block consist of a set of SQL statements, clubbed together and passes
to the oracle engine entirely. A PL/SQL block has definite structure which can be divided into sections:-
i. Declaration Section:- This is the first section of PL/SQL in which we can declare and initialize memory
variable. Once declared they can be used in SQL for data manipulation.
ii. Begin Section:- It consist of SQL and PL/SQL statement which describes processes that has to be applied to
table data.
Actual data manipulation, retrieval, looping, branching, constructs are specified here.
iii. Exception Section:- This section deals with error handling and makeup the PL/SQL code block.
iv. End Section:- This section marks the end of a PL/SQL code block.

Displaying messages on VDU screen.


Programming tool requires a method through which messages can be displayed to the user on
the VDU screen. DBMS_OUTPUT is a package that includes a number of procedure and functions. This function can
also be used to display on screen.
To display messages to the user the serveroutput should be set as on. Serveroutput is
an SQL* plus environment parameter that display the information passes as a parameter to the put_line( ). The put_line(
) puts a piece of information in the package buffer followed by and end of line marker. It can also be used to display to
the user for using this we use the following syntax:-

15
Set serveroutput on;

Dbms_output.put_line(„Messages‟);

Aim:-
Write a procedure in PL/SQL which print your name and mob number.

Source code:-
Set serveroutput on;
Begin
Dbms_output.put_line(„Name:- MONU KUMAR‟);
Dbms_output.put_line(„Mob.:-9852645692‟);
End;

Constants:-
PL/SQL and Oracle both have their foundations in SQL. Most PL/SQL data types are native to Oracle data
dictionary. The defaults data type can be declared in PL/SQL are:-
i. Number
ii. Char
iii. Date
iv. Booleans
The % type attributes provides for further integration. PL/SQL can use the % type attribute to
declare variable based on definition of column in a table. If a column attribute changes the variable attribute will change
as well as. This provides for data independence reduce maintenance cost and allow programs to adopt to change made
to the table.

Variables:-
We know that the variable is a memory container which is used to store run time value and intermediate
result of any process for later operation or hold the intermediate result value. It plays a very vital role in any
programming language similar to another language in PL/SQL. We can also use variable after the declaration. A
PL/SQL variable name must begin with a character and can be followed by 29 character and reserve words cannot be
used as variable name and space cannot be used as variable name, and by using the assignment operator := we can
assign the value of variable.

 Write a program which accept two number and print the sum of given number.
Declare
a number(2);
b number(2);
c number(3);
begin
c=0
dbms_output.put_line(„enter 1st no:-„);

16
a:=&a;
dbms_output.put_line(„enter 2nd no:-„);
b:=&b;
dbms_output.put_line(„sum=||c);
end;

 Write a program which accept principal amount, duration, and rate of interest from user and calculate
simple interest.
Declare
P number(5);
R number(5,2);
T number(3);
SI number(8);
Begin
Si=0;
dbms_output.put_line(„Enter principal Amount:-„);
p:=&p;
dbms_output.put_line(„enter Rate of interest:-„);
R:=&R;
dbms_output.put_line(„Enter no. of months:-„);
T:=&T;
SI= (PRT/100);
dbms_output.put_line(„S.I=||SI);
end;

Iterative Control:-
The iterative control indicates the ability to report or skip sections of a code block. A loop marks a sequence of a
statement that has to be reported. The keyword loop has to be placed before the first statement in the sequence of the
statement is to be repeated, while the keyword end loop is placed immediately after the last statement in the sequence.
Once a loop begins to execute it will go forever. Else a conditional statement that control the no of time of a loop is
executed always completes loops. In PL/SQL we use following types of loop:-
i. Loop….End loop;
ii. While….End loop;
iii. For….End loop;

17
Loop….End loop:-
This is the simple statement of a loop which performs repetition work till specific no of times. The keyword loop should
be placed before the first statement in the sequence and the keyword end loop should be written at the end of the
sequence to end the loop.

Syntax:-
Loop
Sequence of statement
End loop;
Ex:-
Write a program which print 1 to 10 number.
Declare
i number:=1;
Begin
Loop
Dbms_output.put_line(to char(i));
i:=i+1;
exit when i=10;
end loop;
end;

While….End loop:-
Here, we define conditions at the starting of loop, then first of all check the condition if it is true then perform iteration otherwise
not done repetition work.

Syntax:-

While <condition>

Loop

Action

End loop;

Ex:- write a program which print the table of given number.

 Declare
A number:=0;
B number:=1;
C number:=0;
Begin
Dbms_output.put_line(„Enter any number‟);
A:=&A;
While B<=10;
Loop

18
C:=A*B;
Dbms_output.put_line(to char(C));
B:=B+1;
End loop;
End;

For….End loop:-
This is another iterative structure of PL/SQL and performs the iteration work for specific number of times. With this variable we
define the start position and end position. By default it is always incremented by one. We define it using a variable.
Syntax:-
For variable in start...End
Loop
Program statement;
End loop;
In the above syntax with for sentences we define initial number for start and end number. By default it
will move one by one. After this sentence we define loop class which performs the iteration work and before this we define a
program statement or group of program statement for iterations. For the ending of this iteration at least we use end loop statement
which indicate the end of the iteration.
Ex:- write a program which print 1 to 10 number.
Declare
A number(2);
Begin
For A in 1..10
Loop
Dbms_output.put_line(A);
End loop;
End;

GoTo Statement:-

The goto statement changes the flow of control within a PL/SQL block. These statements allow execution of a section of code
which is not in the normal flow of control. The entry point into such a block of code is mark using the tags <<user defined name>>.
The goto statement can then make use of their user defined name to jump into that block of code for execution.
Syntax:-
Goto <<user defined name>>
Ex:-
Declare
a number(2);
b number(2);
c number(3);
Begin
a=1;
b=2;
c=0;
<<XYZ>>
C:=a*b;
Dbms_output.put_line(c);
If a<=10 then
Goto abc;
Endif;
<<abc>>
A:=a+1;
Goto xyz;
End;

19
PL/SQL transaction:-
The series of one or more SQL statements that are logically related that is termed as/known as transaction.
Oracle treats this logical unit as a single entity. Oracle treats changes to table data as a two step process. First the changes requested
are done to make these changes permanent to use commit statement and for undo we use rollback statement.
A transaction can be closed by using either a commit or rollback statement. By using
these statement table data can be changes or all the changes made to the table data undone.

Commit:-
A commit ends the current transaction and makes permanent any changes made during the transaction. All the
transaction lock acquired on the table are released.
Syntax:- Commit

Rollback:-
A rollback does exactly the opposite of commit. It ends the transaction but undo any changes made during the
transaction. All transactional lock acquire on table are released.
Syntax:- Rollback to savepoint savepointname;

Savepoint:-
Savepoint marks save the current point in the processing of a transaction when a savepoint is used with rollback
statement parts of transaction can be undone. An active savepoint is one that is specified since the last commit or rollback.
Syntax:- savepoint savepointname;

Cursor:-
The oracle engine uses a work area for its internal processing in order to execute an SQL statement. This work area is
private to SQL‟s operation and it is called cursor. The data that is stored in the cursor is called cursor active data shell. When a
cursor is loaded gets multiple via to via query the oracle engine open and maintain a row pointer depending upon user request. In
view data row pointer with the cursors active data shell. The cursors are classified into two
categories.
i. Implicit cursor(internal)
ii. Explicit cursor(external)

The oracle engine for its internal processing opens a cursor that is known as implicit cursor and
another one is user defined cursor. A user opens a cursor for processing of data that is known as explicit cursor.

Implicit and explicit Cursors have four

Begin

Update result set maths=maths+10

Where roll:=roll;

If %FOUND then

Dbms_output.put_line(“Marks Increased”);

Endif; attributes:-

Attributes name Description

i. %ISOPEN Return TRUE if cursor is open, FALSE otherwise.


ii. %FOUND Return TRUE if record was fetched successfully, FALSE otherwise.
iii. %NOTFOUND Return TRUE if record was not fetched successfully, FALSE otherwise.
iv. %ROWCOUNT Return number of record processed from the cursor.

End;

20
Trigger:-

The trigger are database objects created via SQL*plus tool on the client and stored on the server in the oracle engine system
tables. The oracle engine allows the user to define procedures that are implicitly executed. When user insert, update or delete
operation perform on table. These procedures are called database trigger.

A trigger provides a highly customizable database management system. A trigger can


perform the following types of management operation:-

i. A trigger can permit DML statement against a table only if they are issued during regular business hours or on pre-
determined week days.
ii. A trigger can be used to keep and audit trial of tables.
iii. It can be used to prevent some invalid transactions.
iv. Enforce complex security Authorization.

A trigger is similar like procedure but there are very few differences like database
triggers and procedures. Trigger does not accept parameters where as procedures need parameters. A trigger is executed oracle
engine itself upon modification of an associated table or its data where as a procedure explicitly called by the user.

TYPES OF TRIGGER

i. ROW TRIGGER

A row trigger is fired each time a row in the table is affected by the triggering statement. If the triggering
statement affected no rows then this type of trigger not execute row trigger should be used when some processing is required
whenever a triggering statement affects a single row in a table.

ii. STATEMENT TRIGGER

A statement trigger is fired once in behalf of triggering statement, independent of the number of rows the
triggering statement affects. The statement trigger should be used when a triggering statement affect row in a table but the
processing required is completely independent of the number of rows affected.

SYNTEX

Create /replace trigger triggername

Before / after

Delete, insert, update [on column] on table name

Declare

….

…..

Begin

Error handling in PL/SQL:-

Every PL/SQL block of code encountered by oracle engine is accepted as a client. The oracle engine will make an attempt to
execute every SQL sentence with the PL/SQL block. When an SQL sentence fails the oracle engine is the first to recognize this
as an exception condition. The oracle engine immediately tries to handle the exception condition and resolve it and this is done
by exception handler.

An exception handler is nothing but a code block in memory that will attempt to resolve the current
exception condition. The oracle engine can recognize every exception conditions that occur in memory to handle very common
and repetitive exception condition. The oracle engine uses named exception handler. The oracle engine has about 15 to 20
name exception handler. The oracle engine can use more than twenty thousand number of exception handler. These exception
handler are identified not by name or but by four integer processed by hyphen (-1414, -1420, -2024). When the oracle engine
invokes an exception handler, the exception handler goes back to the PL/SQL block from which the exception condition was

21
raised. The exception handler scans the PL/SQL block for the existence of an exception section within the PL/SQL block. If an
exception section within the PL/SQL block exists the exception handler scans the first work after the action word when within
the exception section.

Syntax:-

When exceptionname then

Program statement;

Normalization:-
Normalization is the process of organising the column and tables of a relational database to reduce data redundcy and improve
data integrity. Normalization is also the process of simplifying the design of a database so that it achives the optimum structure.
It reduce and eliminate redund data in normalization data integrity is assured. It was first proposed by Dr. E.F CODD as an
internal part of a relational model.

Normalization involves arranging attribute table based on dependencies between attributes


ensuring that the dependencies are properly enforced by database integrity constrants. Normalization is completed through
applying some formal rules either by a process of synthasis or decomposition. The synthasis creates a normalised database
design based on a known set of dependency. The decomposition takes an existing database design and improves it based on the
known set of dependency. The E.F CODD the inventor of relational model introduces the concept of normalization as in 1970
and that is known as first normal form (1NF). He also define second normal form (2NF) and third normal form (3NF) in 1971
and E.F CODD and Raymond F. Boycee define B.C.N.F (Boycee Normal Normal Form) in 1974.

1NF:- The 1NF is a property of relations in relational database.

2NF:- Second Normal Form is a normal form used in database normalization, a table that is in 1NF must meet additional
criteria if it is qualify for 2NF.

3NF:- Third Normal Form is a normal form that is used in database design to reduce the duplication of data that is
used____________ and ensures refrential integrity and it includes database processing and minimise storage cost.

22
4NF:- The 4NF is introduced by Ronald Fagin in 1977. This is the next level of normalization after BNCF. 4NF is concerned
with a more general type of dependency known as multi valued dependency.

23

Anda mungkin juga menyukai