Вы находитесь на странице: 1из 65

Jatin Bhatia, 10165

Experiment 1
Aim: Describe Data Base Management System.
DBMS (Data Base Management System): Is a system or computer software that is
designed for the purpose to manage information or databases in such way so that data
storage and retrieval of information gets easy, so we can easily say that DBMS defines
what will be the structure for information storage and in addition to it facilitates in data
manipulation. The common examples of Data Base Management Systems are Microsoft
Access, DB2, Oracle, SQL Server etc. There are some common goals while using
DBMS.

(1) Security.
(2) Backup and Replication.
(3) Change and Access Logging.
(4) Automated Optimization.
(5) Policy Enforcement.
(6) Query Ability.
(7) Meta Data Repository.
(8) Computation.
There are three most commonly used database models.
(1) Hierarchal: A hierarchical database model is a data model in which the data is
organized into a tree-like structure. The structure allows representing information using
parent/child relationships: each parent can have many children, but each child has only
one parent (also known as a 1-to-many relationship). All attributes of a specific record
are listed under an entity type.
(2) Network: The network structure consists of more complex relationships. Unlike the
hierarchical structure, it can relate to many records and accesses them by following one
of several paths. In other words, this structure allows for many-to-many relationships.
(3) Relational: The relational structure is the most commonly used today. It is used by
mainframe, midrange and microcomputer systems. It uses two-dimensional rows and
columns to store data. The tables of records can be connected by common key values.
The model is not easy for the end user to run queries with because it may require a
complex combination of many tables.
Jatin Bhatia, 10165

Advantages of DBMS over File Processing System:

The DBMS has a number of advantages as compared to traditional computer file
processing approach.

1. Controlling Data Redundancy:
In non-database systems (traditional computer file processing), each application program
has its own files. In this case, the duplicated copies of the same data are created at many
places. In DBMS, all the data of an organization is integrated into a single database. The
data is recorded at only one place in the database and it is not duplicated. For example,
the dean's faculty file and the faculty payroll file contain several items that are identical.
When they are converted into database, the data is integrated into a single database so
that multiple copies of the same data are reduced to-single copy.
In DBMS, the data redundancy can be controlled or reduced but is not removed
completely. Sometimes, it is necessary to create duplicate copies of the same data items
in order to relate tables with each other. By controlling the data redundancy, you can save
storage space. Similarly, it is useful for retrieving data from database using queries.

2. Data Consistency:
By controlling the data redundancy, the data consistency is obtained. If a data item
appears only once, any update to its value has to be performed only once and the updated
value (new value of item) is immediately available to all users.
If the DBMS has reduced redundancy to a minimum level, the database system enforces
consistency. It means that when a data item appears more than once in the database and is
updated, the DBMS automatically updates each occurrence of a data item in the database.

3. Data Sharing:
In DBMS, data can be shared by authorized users of the organization. The DBA manages
the data and gives rights to users to access the data. Many users can be authorized to
access the same set of information simultaneously. The remote users can also share same
data. Similarly, the data of same database can be shared between different application
programs.

4. Data Integration:
In DBMS, data in database is stored in tables. A single database contains multiple tables
and relationships can be created between tables (or associated data entities). This makes
easy to retrieve and update data.
Jatin Bhatia, 10165


5. Integrity Constraints:
Integrity constraints or consistency rules can be applied to database so that the correct
data can be entered into database. The constraints may be applied to data item within a
single record or they may be applied to relationships between records.

Examples:
The examples of integrity constraints are:
(i) 'Issue Date' in a library system cannot be later than the corresponding 'Return Date' of
a book.
(ii) Maximum obtained marks in a subject cannot exceed 100.
(iii) Registration number of BCS and MCS students must start with 'BCS' and 'MCS'
respectively etc.

There are also some standard constraints that are intrinsic in most of the DBMSs. These
are;
Constraint Name Description
PRIMARY KEY Designates a column or combination of columns as
Primary Key and therefore, values of columns cannot be
repeated or left blank.
FOREIGN KEY Relates one table with another table.
UNIQUE Specifies that values of a column or combination of
columns cannot be repeated.
NOT NULL Specifies that a column cannot contain empty values.
CHECK Specifies a condition which each row of a table must
satisfy.

6. Data Security:
Data security is the protection of the database from unauthorized users. Only the
authorized persons are allowed to access the database. Some of the users may be allowed
to access only a part of database i.e., the data that is related to them or related to their
department. Mostly, the DBA or head of a department can access all the data in the
database. Some users may be permitted only to retrieve data, whereas others are allowed
to retrieve as well as to update data. The database access is controlled by the DBA. He
creates the accounts of users and gives rights to access the database. Typically, users or
group of users are given usernames protected by passwords.
Most of the DBMSs provide the security sub-system, which the DBA uses to create
accounts of users and to specify account restrictions. The user enters his/her account
number (or username) and password to access the data from database. For example, if
you have an account of e-mail in the "hotmail.com" (a popular website), then you have to
Jatin Bhatia, 10165

give your correct username and password to access your account of e-mail. Similarly,
when you insert your ATM card into the Auto Teller Machine (ATM) in a bank, the
machine reads your ID number printed on the card and then asks you to enter your pin
code (or password). In this way, you can access your account.

7. Data Atomicity:
A transaction in commercial databases is referred to as atomic unit of work. For example,
when you purchase something from a point of sale (POS) terminal, a number of tasks are
performed such as;
Company stock is updated.
Amount is added in company's account.
Sales person's commission increases etc.
All these tasks collectively are called an atomic unit of work or transaction. These tasks
must be completed in all; otherwise partially completed tasks are rolled back. Thus
through DBMS, it is ensured that only consistent data exists within the database.

8. Database Access Language:
Most of the DBMSs provide SQL as standard database access language. It is used to
access data from multiple tables of a database.

9. Development of Application:
The cost and time for developing new applications is also reduced. The DBMS provides
tools that can be used to develop application programs. For example, some wizards are
available to generate Forms and Reports. Stored procedures (stored on server side) also
reduce the size of application programs.

10. Creating Forms:
Form is very important object of DBMS. You can create Forms very easily and quickly in
DBMS, Once a Form is created, it can be used many times and it can be modified very
easily. The created Forms are also saved along with database and behave like a software
component.
A Form provides very easy way (user-friendly interface) to enter data into database, edit
data, and display data from database. The non-technical users can also perform various
operations on databases through Forms without going into the technical details of a
database.

11. Report Writers:
Most of the DBMSs provide the report writer tools used to create reports. The users can
create reports very easily and quickly. Once a report is created, it can be used many times
Jatin Bhatia, 10165

and it can be modified very easily. The created reports are also saved along with database
and behave like a software component.

12. Control Over Concurrency:
In a computer file-based system, if two users are allowed to access data simultaneously, it
is possible that they will interfere with each other. For example, if both users attempt to
perform update operation on the same record, then one may overwrite the values recorded
by the other. Most DBMSs have sub-systems to control the concurrency so that
transactions are always recorded" with accuracy.

13. Backup and Recovery Procedures:
In a computer file-based system, the user creates the backup of data regularly to protect
the valuable data from damaging due to failures to the computer system or application
program. It is a time consuming method, if volume of data is large. Most of the DBMSs
provide the 'backup and recovery' sub-systems that automatically create the backup of
data and restore data if required. For example, if the computer system fails in the middle
(or end) of an update operation of the program, the recovery sub-system is responsible for
making sure that the database is restored to the state it was in before the program started
executing.

14. Data Independence:
The separation of data structure of database from the application program that is used to
access data from database is called data independence. In DBMS, database and
application programs are separated from each other. The DBMS sits in between them.
You can easily change the structure of database without modifying the application
program. For example you can modify the size or data type of a data items (fields of a
database table). On the other hand, in computer file-based system, the structure of data
items are built into the individual application programs. Thus the data is dependent on the
data file and vice versa.

15. Advanced Capabilities:
DBMS also provides advance capabilities for online access and reporting of data through
Internet. Today, most of the database systems are online. The database technology is used
in conjunction with Internet technology to access data on the web servers.

Disadvantages of Database Management System (DBMS):

Although there are many advantages but the DBMS may also have some minor
disadvantages. These are:

Jatin Bhatia, 10165

1. Cost of Hardware & Software:
A processor with high speed of data processing and memory of large size is required to
run the DBMS software. It means that you have to upgrade the hardware used for file-
based system. Similarly, DBMS software is also very costly.

2. Cost of Data Conversion:
When a computer file-based system is replaced with a database system, the data stored
into data file must be converted to database files. It is difficult and time consuming
method to convert data of data files into database. You have to hire DBA (or database
designer) and system designer along with application programmers; Alternatively, you
have to take the services of some software houses. So a lot of money has to be paid for
developing database and related software.

3. Cost of Staff Training:
Most DBMSs are often complex systems so the training for users to use the DBMS is
required. Training is required at all levels, including programming, application
development, and database administration. The organization has to pay a lot of amount
on the training of staff to run the DBMS.

4. Appointing Technical Staff:
The trained technical persons such as database administrator and application
programmers etc are required to handle the DBMS. You have to pay handsome salaries to
these persons. Therefore, the system cost increases.

5. Database Failures:
In most of the organizations, all data is integrated into a single database. If database is
corrupted due to power failure or it is corrupted on the storage media, then our valuable
data may be lost or whole system stops.











Jatin Bhatia, 10165

Experiment 2
AIM: To create a table in SQL.
Theory: SQL stands for Structured Query Language. SQL lets you access and
manipulate databases using various commands with a particular syntax.The query and
update commands form the DML part of SQL:
SELECT - extracts data from a database
The most important DDL statements in SQL are:
CREATE DATABASE - creates a new database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
SYNTAX:
Create table syntax:
CREATE TABLE table_name
(
column_name1 data_type constraint1,
column_name2 data_type constraint2,
column_name3 data_type constraint3,
....
)
* constraint field are optional.
View created table:
To view the table to be created we use Des command.
Desc table_name;
Project for Management of Data Base System
Library Management System:
Jatin Bhatia, 10165

We have created a database that manages a library system using SQL language. The table
with there screenshots are:
Table 1: Staff
Attributes: Employ_ID, Name,Departement, DOB, Book_ID, Membership_Code










Jatin Bhatia, 10165


Table 2:Students
Attributes: RollNo, Name, Branch, Membership_Code, Book_ID









Jatin Bhatia, 10165


Table 3: Books Issued
Attributes:Book_ID, Name_of_Book, Author, Semester, Date_of_issue,
Admin_ID,Issuer_ID, Issuer_ID








Jatin Bhatia, 10165


Table 4:Book
Book_ID, Name, Author, Semester







Jatin Bhatia, 10165

Table 5: Fine
Issuer_ID, Name, Book_Name, Price, Fine












Jatin Bhatia, 10165

Experiment 3
AIM: To alter a created table in SQL.
Theory: Alter command is used to alter or modify the schema of the required table. Alter
command can be used for various tasks in a table some of them are:
To add an attribute inside a table.
To rename an attribute inside a table.
To delete a given attribute in a table.
To alter the data type of the attribute in a table.
To rename a table.
To add a constraint (like Primary Key) to a given attribute.
To delete a constraint (like Not Null) to a given attribute.
SYNTAX:
To add an attribute inside a table.
alter table table_name
add(columnname 1 datatype1 constraint1(optional),
columnname 2 datatype2 constraint2(optional),
-------------------------------
columnname n datatypen
);
To rename an attribute inside a table.
Alter table table_name
Rename column old_name to new_name
;
To delete a given attribute in a table
Alter table table_name
Drop (attribute_name);
Jatin Bhatia, 10165

To alter the data type of the attribute in a table.
Alter table table_name
Modify ( attribute_name1 new datatype1,
attribute_name2 new datatype2,
--------------------------------------
attribute_namen new datatypen
);
To rename a table
Alter table table_name
Rename to new table_name
;
To add a constraint (like Primary Key) to a given attribute.
Alter table table_name
Add (constraint constraint_label constraint name (attribute_name))
;
To delete a constraint (like Not Null) to a given attribute
Alter table table_name
Drop constraint constraint_label
;
Examples of above commands with their screen shots applied on our Library
Management Database are shown as follows:

Jatin Bhatia, 10165

Adding an attribute price of data type number in table book.






Jatin Bhatia, 10165

To rename column Date_of_birth to DOB.





Jatin Bhatia, 10165

To drop an attribute price in a table book.






Jatin Bhatia, 10165

To modify the data type of employee_id, book_id and membership_code to
varchar, number and number respectively.



Jatin Bhatia, 10165

To change the table name Staff to Employee.





Jatin Bhatia, 10165

To add a Primary Key constraint to Book_ID.







Jatin Bhatia, 10165

To delete a Primary Key constraint on Book_ID.








Jatin Bhatia, 10165

To rename column name name_of_books to Book_name.






Jatin Bhatia, 10165

Experiment 4
AIM: To insert records in tables created in SQL?

THEORY: Insert command is a DML command defined in SQL. Data Manipulation
Language (DML) statements are used for managing data within schema objects. Insert
command is used to insert records in a table.

SYNTAX:
A record can be inserted in a table in many formats. These are:
Insert into table_name
(col1,col2,col3,.,coln)
Values(val1,val2,val3,.,valn);

Insert all
Into table_name values(val1,val2,.,valn) //for row1
Into table_name values(val1,val2,.,valn) //for row2
.
Into table_name values(val1,val2,.,valn) //for rown
Select * from dual;

Insert into table_name
Values(&col1,&col2,&col3,..,&coln);
Enter the value of col1:val1
Enter the value of col2:val2
Enter the value of col3:val3
...
Enter the value of coln:valn
Rows added

To view the inserted records:
Select * from table_name;

Examples of above commands with their screen shots applied on our Library
Management Database are shown in the following pages:


Jatin Bhatia, 10165

Inserting records in table Employee



Jatin Bhatia, 10165


Inserting records in table Student

Jatin Bhatia, 10165



Jatin Bhatia, 10165


Inserting records in table Book


Jatin Bhatia, 10165



Jatin Bhatia, 10165

Inserting records in the table Book_issued


Jatin Bhatia, 10165


Inserting records in table Fine

Jatin Bhatia, 10165





Jatin Bhatia, 10165

Experiment 5
AIM: To delete records in tables created in SQL?

THEORY: Delete command is also a DML command. It is used to delete records in the
required table. While deleting a row if we need to apply a condition to it, then we have to
use this command with where.

SYNTAX: There are various formats in which the delete command can be used. Some of
them are:
Delete from table_name
where condition;
Delete from table_name; //It deletes all rows from table


Examples of above commands with their screen shots applied on our Library
Management Database are shown in the following pages:
Deletion command applied on table student:
(using where condition 4 screen shots)

Jatin Bhatia, 10165



Jatin Bhatia, 10165



Delete command on table student(deleting complete rows)







Jatin Bhatia, 10165

Experiment 6
AIM: To use group by command in table created in SQL?
THEORY: The GROUP BY statement is used in conjunction with the aggregate
functions to group the result-set by one or more columns and display it to user. SQL
aggregate functions are: Sum, Min, Max, Count, Avg. To give a condition while using
the group by function we can use the statement having with it.
SYNTAX:
Select aggregate function (column1)
From table_name
Group by column1;
Select aggregate function (column1)
From table_name
Group by column1
Having condition;

Examples of above commands with their screen shots applied on our Library
Management Database are shown in the following pages:












Jatin Bhatia, 10165

Screenshot1: Here we can see that the fine attribute is added from the table fine
grouped according to the price. For example sum of fine on all the books whose
price is 400 is 180 as shown in the output arranged in ascending order according to
the price. Here Sum is an aggregate function used.











Jatin Bhatia, 10165

Screenshot2: Here we have count the number of time the fine issued on a same
price book( that is grouped by price)
For example number of times the book with price 400 is fined is 3 as shown in the
output and verified by the table displayed in screenshot1.























Jatin Bhatia, 10165

Screenshot3: Here I have used a having statement with group by to give a
condition inside my command. Here sum of fine will be grouped by according to
the price as in screenshot1. But the only difference here will be that the command
will be applicable only for the rows or records that have price>300 as shown in the
output.














Jatin Bhatia, 10165

Screenshot4: Here we count number of books for each sem. For example for 4 sem
there are 4 books as shown in output.
















Jatin Bhatia, 10165

Screenshot5:Here same operation is done as in screenshot 4 but here we used a
condition by using having command with group by.

















Jatin Bhatia, 10165

Experiment 7
AIM: To arrange the data in a table created in SQL?

THEORY: To arrange a data inside a table created in SQL the command used is order by.
Order by command arranges the data in table in ascending (by default) or descending
order according to our preference.
SYNTAX:
This syntax arranges the data in ascending order by default applied on the column
column_name.
Select * from table_name
Order by column_name;

This syntax arranges the data in descending order (desc) applied on the column
column_name.
Select * from table_name
Order by column_name desc;

Examples of above commands with their screen shots are shown in the following pages:

















Jatin Bhatia, 10165

Screenshot1: Here the table is arranged according to book_id.














Jatin Bhatia, 10165

Screenshot2: Here table is arranged according to name attribute alphabetically and
according to sem.




Jatin Bhatia, 10165

Experiment 8
AIM: To modify the data in tables created in SQL?

THEORY: To modify the records inserted in table we have to use the command update.
We have to set the value of a particular column where the condition identifies the
particular tuple or row.
SYNTAX:
To make change in a single column:
Update table_name
Set column=value/expression
Where condtion;
To make change in multiple column:
Update table_name
Set column1=value/expression , column2=value/expression
Where condtion;
When more than one condition is to be implemented:
Update table_name
Set column=value/expression
Where condtion1 AND condition2;
Examples of above commands with their screen shots applied on our Library
Management Database are shown in the following pages:
Screenshot1:Original Table book


Jatin Bhatia, 10165

Screenshot2: Here multiple values are set.








Jatin Bhatia, 10165

Screenshot3: Here we have given multiple conditions.



Jatin Bhatia, 10165

Screenshot4: Here one condition is given.









Jatin Bhatia, 10165

Experiment 9
AIM: To apply Join operations in tables created in SQL?

THEORY: Join operation combines records from two or more tables in a database. It
creates a set that can be saved as a table or used as it is. A JOIN is a means for combining
fields from two tables by using values common to each. There are different types of join
operation:-
Cross Join: It is also known as Cartesian product of two tables. It returns the
Cartesian product of rows from tables in the join. In other words, it will produce
rows which combine each row from the first table with each row from the second
table.
Inner Join: It is also known as Equi-Join or Simple Join operation. It is a specific
type of comparator-based join, or theta join, that uses only equality comparisons in
the join-predicate. Using other comparison operators (such as <) disqualifies a join
as an equi-join.
Outer Join: An outer join does not require each record in the two joined tables to
have a matching record. The joined table retains each recordeven if no other
matching record exists. Outer joins subdivide further into left outer joins, right
outer joins, and full outer joins, depending on which table(s) one retains the rows
from (left, right, or both).
Self Join: A self-join is joining a table to itself.
SYNTAX: Syntax for different type of join operations is as follows:
Cross Join/Cartesian Product:
Select * from
Table1, table2
Where condition1;
Inner Join/Equi-Join/Simple Join
Select table1.column, table2.column
From table1, table2
Where table1.column=table2.column;



Jatin Bhatia, 10165

Left Outer Join
Select table1.column, table2.column
From table1, table2
Where table1.column(+)=table2.column;
OR
Select from table1 leftouterjoin table2
On table1.column=table2.column;
Right Outer Join
Select table1.column, table2.column
From table1, table2
Where table1.column=table2.column(+);
OR
Select from table1 rightouterjoin table2
On table1.column=table2.column;
Full Outer Join
Select from table1 fullouterjoin table2
On table1.column=table2.column;
Self Join
Select column1, column2, cloumn3
From table1 a, table1 b
Where a.column1=b.column2;

Table Alias: In the above syntax we used a for table1 and b for table 2. This method
reduces the code length and gives the programmer a shortcut in SQL; a and b are
called the table alias and can be used inside the commands whenever required.

Examples of above commands with their screen shots are shown in the following pages:



Jatin Bhatia, 10165

SCREENSHOT1:All the Join operations will be done on the following tables
(Employee and departement). The table is shown in the screenshot along with the
tuples.

SCREENSHOT2: It describes the cross join/Cartesian product operation on the
two tables with and without condition. In one part a condition is given which
reduces the number of tuples and in second part 24 rows are selected.



Jatin Bhatia, 10165



SCREENSHOT3: It describes the inner join operation.

Jatin Bhatia, 10165

SCREENSHOT4: It describes the left outer join operation on the tables.

SCREENSHOT5: It describes the right outer join operation.

SCREENSHOT6: It describes full outer join operation.


Jatin Bhatia, 10165

Experiment 10
AIM: To insert data in a table with the help of subquery?
THEORY: Subquery or Inner query or Nested query is a query in a query. A subquery is
usually added in the WHERE Clause of the sql statement. Most of the time, a subquery is
used when you know how to search for a value using a SELECT statement, but do not
know the exact value. Subqueries are an alternate way of returning data from multiple
tables. During execution of a subquery command in SQL, the innermost query executes
first.
Subqueries can be used with the following sql statements along with the comparison
operators like =, <, >, >=, <= etc.
SYNTAX:
To copy schema of one table to another.
Create table <newtable_name> as
(select * from <oldtable_name> where 1>2);

To copy schema as well as data from one table to another.
Create table <newtable_name> as
(select * from <oldtable_name>);

To copy schema and data from one table to another with some conditions.
Create table <newtable_name> as
(select * from <oldtable_name> where condition);
Examples of above commands with their screen shots are shown in the following pages:






Jatin Bhatia, 10165

Screenshot1: The schema of a table student1 is copied into another table student2.



Screenshot2: The schema as well as data of table student1 is copied into the table
student3.






Jatin Bhatia, 10165

Screenshot3: A new table student4 is created from student1. Student4 contain data
of all the students that have se as there department.












Jatin Bhatia, 10165

Experiment 11
AIM: To retrieve, delete, and update the date in a table using subquery?

THEORY: Subquery or Inner query or Nested query is a query in a query. A subquery is
usually added in the WHERE Clause of the sql statement. A subquery can also be use to
retrieve, delete and update the information or data in a table created in SQL.
The subqueries can be applied on same as well as on different table to get the required
results.
There are 2 types of retrieval in SQL: Single Row and Multiple Row.
When inner query returns a single tuple as its query output then its single row retrieval
else it is multiple row retrieval.
SYNTAX:
To retrieve data from a table.
Select select_list
From table
Where expression_operator
(select select_list
from table);

To delete data from the table
Delete from <table_name> where <column_name>
In(subquery);

To update data in a table.
Update <table_name>
Set<column_name1>= (subquery1)
<column_name2>= (subquery2)
Where condition;
Examples of above commands with their screen shots are shown in the following pages:


Jatin Bhatia, 10165

Screenshot1: Here I have retrieved the data from the table student. List of all the
students are displayed except the student having mechanical department. It is an
example of multiple row retrieval of data.







Jatin Bhatia, 10165


Screenshot2: This screenshot describe the single row retrieval of data from table
student1


Screenshot3: All the student having branch cse are deleted from the table student1
using a subquery.

Jatin Bhatia, 10165

Screenshot4: Here I have updated the table student1 using a subquery. The name of
the student with roll no 10160 is changed to karma as displayed below.















Jatin Bhatia, 10165

Experiment 12
AIM: Describe PL/SQL (Procedural Language/Structured Query Language)?
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's
procedural extension language for SQL and the Oracle relational database. PL/SQL's
general syntax resembles that of Ada or Pascal.PL/SQL is one of three key programming
languages embedded in the Oracle Database, along with SQL itself and Java.
PL/SQL is Oracle's procedural language extension to SQL, the relational database
language. PL/SQL fully integrates
modern software engineering features such as data encapsulation, information hiding,
overloading, and exception handling, and so brings state-of-the-art programming to the
ORACLE Server and a variety of ORACLE tools

Overview of PL/SQL:
With PL/SQL, you can use SQL statements to manipulate ORACLE data and flow-of-
control statements to process the data. Moreover, you can declare constants and variables,
define subprograms (procedures and functions), and trap runtime errors. Thus, PL/SQL
combines the data manipulating power of SQL with the data processing power of
procedural languages.
PL/SQL is a block-structured language. That is, the basic units (procedures, functions,
and anonymous blocks) that make up a PL/SQL program are logical blocks, which can
contain any number of nested sub-blocks. Typically, each logical block corresponds to a
problem or subproblem to be solved. A block (or sub-block) lets you group logically
related declarations and statements. That way you can place declarations close to where
they are used. The declarations are local to the block and cease to exist when the block
completes.

[DECLARE-- declarations]
BEGIN
-- statements
[EXCEPTION-- handlers]
END;
PL/SQL Tables
PL/SQL provides two composite datatypes: TABLE and RECORD. Objects of type
TABLE are called PL/SQL tables, which are modeled as (but not the same as) database
tables. PL/SQL tables use a primary key to give you array-like
access to rows.
Jatin Bhatia, 10165

Like the size of a database table, the size of a PL/SQL table is unconstrained. That is, the
number of rows in a PL/SQL table can increase dynamically. The PL/SQL table grows as
new rows are added.
PL/SQL tables can have one column and a primary key, neither of which can be named.
The column can belong to any scalar type, but the primary key must belong to type
BINARY_INTEGER.

Interaction With ORACLE:
SQL Support
By extending SQL, PL/SQL offers a unique combination of power and ease of use. You
can manipulate ORACLE data flexibly and safely because PL/SQL supports all SQL data
manipulation commands (except EXPLAIN PLAN), transaction control commands,
functions, pseudocolumns, and operators. However, PL/SQL does not support data
definition commands such as CREATE, session control commands such as SET ROLES,
or the system control command ALTER SYSTEM.

Data Manipulation
To manipulate ORACLE data, you use the INSERT, UPDATE, DELETE, SELECT, and
LOCK TABLE commands.

Transaction Control
ORACLE is transaction oriented; that is, ORACLE uses transactions to ensure data
integrity. A transaction is a series of SQL data manipulation statements that does a
logical unit of work. For example, two UPDATE statements might
credit one bank account and debit another. At the same instant, ORACLE makes
permanent or undoes all database changes made by a transaction. If your program fails in
the middle of a transaction, ORACLE detects the error and rolls back the transaction.
Hence, the database is restored to its former state automatically.

You use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION
commands to control transactions.
COMMIT makes permanent any database changes made during the current transaction.
Until you commit your changes, other users cannot see them. ROLLBACK ends the
current transaction and undoes any changes made since the transaction began.
SAVEPOINT marks the current point in the processing of a transaction. Used with
ROLLBACK, undoes part of a transaction. SET TRANSACTION establishes a read-only
transaction

Jatin Bhatia, 10165

CONTROL STRUCTURES
According to the structure theorem, any computer program can be written using the basic
control structures which can be combined in any way necessary to deal with a given
problem.
The selection structure tests a condition, then executes one sequence of statements
instead of another, depending on whether the condition is true or false. A condition is any
variable or expression that returns a Boolean value (TRUE, FALSE, or NULL). The
iteration structure executes a sequence of statements repeatedly as long as a condition
holds true. The sequence structure simply executes a sequence of statements in the order
in which they occur.
Conditional Control: IF Statements
Often, it is necessary to take alternative actions depending on circumstances. The IF
statement lets you execute a sequence of statements conditionally. That is, whether the
sequence is executed or not depends on the value of a
condition. There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-
THEN-ELSIF.
The third form of IF statement uses the keyword ELSIF (NOT ELSEIF) to introduce
additional conditions, as follows:
IF condition1 THEN
sequence_of_statements1;
ELSIF condition2 THEN
sequence_of_statements2;
ELSE
sequence_of_statements3;
15
END IF;
Iterative Control: LOOP and EXIT Statements
LOOP statements let you execute a sequence of statements multiple times. There are
three forms of LOOP statements:
LOOP, WHILE-LOOP, and FOR-LOOP.
LOOP
The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a
sequence of statements between
the keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements3;
...
END LOOP;
Jatin Bhatia, 10165

With each iteration of the loop, the sequence of statements is executed, then control
resumes at the top of the loop. If further processing is undesirable or impossible, you can
use the EXIT statement to complete the loop. You can place
one or more EXIT statements anywhere inside a loop, but nowhere outside a loop. There
are two forms of EXIT statements: EXIT and EXIT-WHEN.
The EXIT statement forces a loop to complete unconditionally. When an EXIT statement
is encountered, the loop completes immediately and control passes to the next statement.
LOOP
...
IF ... THEN
...
EXIT; -- exit loop immediately
END IF;
END LOOP;
-- control resumes here
The EXIT-WHEN statement allows a loop to complete conditionally. When the EXIT
statement is encountered, the condition in the WHEN clause is evaluated. If the condition
evaluates to TRUE, the loop completes and control passes to the next statement after the
loop.
LOOP
FETCH c1 INTO ...
EXIT WHEN c1%NOTFOUND; -- exit loop if condition is true
...
END LOOP;
CLOSE c1;
Until the condition evaluates to TRUE, the loop cannot complete. So, statements within
the loop must change the value
of the condition.
Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier enclosed
by double angle brackets, must
appear at the beginning of the LOOP statement, as follows:
<<label_name>>
LOOP
sequence_of_statements;
...
16
END LOOP [label_name];
Optionally, the label name can also appear at the end of the LOOP statement.
Jatin Bhatia, 10165

With either form of EXIT statement, you can complete not only the current loop, but any
enclosing loop. Simply label the enclosing loop that you want to complete, then use the
label in an EXIT statement.
<<outer>>
LOOP
...
LOOP
...
EXIT outer WHEN ... -- exit both loops
END LOOP;
...
END LOOP outer;
WHILE-LOOP
The WHILE-LOOP statement associates a condition with a sequence of statements
enclosed by the keywords LOOP and END LOOP, as follows:
WHILE condition LOOP
sequence_of_statements;
...
END LOOP;
Before each iteration of the loop, the condition is evaluated. If the condition evaluates to
TRUE, the sequence of statements is executed, then control resumes at the top of the
loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and control
passes to the next statement. Since the condition is tested at the top of the loop, the
sequence might execute zero times.
FOR-LOOP
Whereas the number of iteration through a WHILE loop is unknown until the loop
completes, the number of iterations through a FOR loop is known before the loop is
entered. FOR loops iterate over a specified range of integers. The range is part of an
iteration scheme, which is enclosed by the keywords FOR and LOOPS.
FOR counter IN [REVERSE] lower_bound..upper_bound LOOP
sequence_of_statements;
...
END LOOP;
The lower bound need not be 1. However, the loop counter increment (or decrement)
must be 1.
PL/SQL lets you determine the loop range dynamically at run time, as the following
example shows:
SELECT COUNT(empno) INTO emp_count FROM emp;
FOR i IN 1..emp_count LOOP
...
Jatin Bhatia, 10165

END LOOP;
17
The loop counter is defined only within the loop. You cannot reference it outside the
loop. You need not explicitly
declare the loop counter because it is implicitly declared as a local variable of type
INTEGER.
The EXIT statement allows a FOR loop to complete prematurely. You can complete not
only the current loop, but any
enclosing loop.

Вам также может понравиться