Professional Documents
Culture Documents
Database is a collection of related data and data is a collection of facts and figures that can
be processed to produce information.
Mostly data represents recordable facts. Data aids in producing information, which is based
on facts. For example, if we have data about marks obtained by all students, we can then
conclude about toppers and average marks.
A database management system stores data in such a way that it becomes easier to retrieve,
manipulate, and produce information.
Characteristics
Traditionally, data was organized in file formats. DBMS was a new concept then, and all the
research was done to make it overcome the deficiencies in traditional style of data
management. A modern DBMS has the following characteristics
Real-world entity A modern DBMS is more realistic and uses real-world entities to
design its architecture. It uses the behavior and attributes too. For example, a school
database may use students as an entity and their age as an attribute.
Relation-based tables DBMS allows entities and relations among them to form
tables. A user can understand the architecture of a database just by looking at the table
names.
Isolation of data and application A database system is entirely different than its
data. A database is an active entity, whereas data is said to be passive, on which the
database works and organizes. DBMS also stores metadata, which is data about data,
to ease its own process.
Less redundancy DBMS follows the rules of normalization, which splits a relation
when any of its attributes is having redundancy in values. Normalization is a
mathematically rich and scientific process that reduces data redundancy.
Query Language DBMS is equipped with query language, which makes it more
efficient to retrieve and manipulate data. A user can apply as many and as different
filtering options as required to retrieve a set of data. Traditionally it was not possible
where file-processing system was used.
--1--
Multiple views DBMS offers multiple views for different users. A user who is in
the Sales department will have a different view of database than a person working in
the Production department. This feature enables the users to have a concentrate view
of the database according to their requirements.
Security Features like multiple views offer security to some extent where users are
unable to access data of other users and departments. DBMS offers methods to
impose constraints while entering data into the database and retrieving the same at a
later stage. DBMS offers many different levels of security features, which enables
multiple users to have different views with different features. For example, a user in
the Sales department cannot see the data that belongs to the Purchase department.
Additionally, it can also be managed how much data of the Sales department should
be displayed to the user. Since a DBMS is not saved on the disk as traditional file
systems, it is very hard for miscreants to break the code.
Users
A typical DBMS has users with different rights and permissions who use it for different
purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly
categorized as follows
Designers Designers are the group of people who actually work on the designing
part of the database. They keep a close watch on what data should be kept and in what
format. They identify and design the whole set of entities, relations, constraints, and
views.
End Users End users are those who actually reap the benefits of having a DBMS.
End users can range from simple viewers who pay attention to the logs or market rates
to sophisticated users such as business analysts.
--3--
DBMS - Architecture
The design of a DBMS depends on its architecture. It can be centralized or decentralized or
hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An ntier architecture divides the whole system into related but independent n modules, which can
be independently modified, altered, changed, or replaced.
In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS
and uses it. Any changes done here will directly be done on the DBMS itself. It does not
provide handy tools for end-users. Database designers and programmers normally prefer to
use single-tier architecture.
If the architecture of DBMS is 2-tier, then it must have an application through which the
DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by
means of an application. Here the application tier is entirely independent of the database in
terms of operation, design, and programming.
3-tier Architecture
A 3-tier architecture separates its tiers from each other based on the complexity of the users
and how they use the data present in the database. It is the most widely used architecture to
design a DBMS.
User (Presentation) Tier End-users operate on this tier and they know nothing
about any existence of the database beyond this layer. At this layer, multiple views of
the database can be provided by the application. All views are generated by
applications that reside in the application tier.
--4--
Multiple-tier database architecture is highly modifiable, as almost all its components are
independent and can be changed independently.
Entity-Relationship Model
Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships
among them. While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.
ER Model is best used for the conceptual design of a database.
ER Model is based on
o one to one
o one to many
o many to one
o many to many
RDBMS
What is RDBMS
RDBMS stands for Relational Database Management Systems..
All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE,
My-SQL and Microsoft Access are based on RDBMS.
It is called Relational Data Base Management System (RDBMS) because it is based on
relational model introduced by E.F. Codd.
How it works
Data is represented in terms of tuples (rows) in RDBMS.
Relational database is most commonly used database. It contains number of tables and each
table has its own primary key.
Due to a collection of organized set of tables, data can be accessed easily in RDBMS.
What is table
The RDBMS database uses tables to store data. A table is a collection of related data entries
and contains rows and columns to store data.
A table is the simplest example of data storage in RDBMS.
Let's see the example of student table.
ID
1
Name
Ajeet
--6--
AGE
COURSE
24
B.Tech
aryan
20
C.A
What is field
Field is a smaller entity of the table which contains specific information about every record in
the table. In the above example, the field in the student table consist of id, name, age, course.
--7--
ARUN
24
M.C.A
What is column
A column is a vertical entity in the table which contains all information associated with a
specific field in a table. For example: "name" is a column in the above table which contains
all information about student's name.
Arun
Aryan
NULL Values
The NULL value of the table specifies that the field has been left blank during record
creation. It is totally different from the value filled with zero or a field that contains space.
Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Entity integrity: It specifies that there should be no duplicate rows in a table.
Domain integrity: It enforces valid entries for a given column by restricting the type, the
format, or the range of values.
Referential integrity: It specifies that rows cannot be deleted, which are used by other
records.
User-defined integrity: It enforces some specific business rules that are defined by users.
These rules are different from entity, domain or referential integrity.
The main differences between DBMS and RDBMS are given below:
No.
DBMS
RDBMS
1
)
2
)
3
)
4
)
5
)
6
)
7
)
DBMS does
not
distributed database.
8
)
9
)
support
What is Database
SQL
What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL
Server use SQL as standard database language.
Also, they are using different dialects, such as:
Why SQL?
Allows users to define the data in database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & precompilers.
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.
What is table ?
The data in RDBMS is stored in database objects called tables. The table is a collection of
related data entries and it consists of columns and rows.
--10--
Remember, a table is the most common and simplest form of data storage in a relational
database.
What is field?
Every table is broken up into smaller entities called fields. The fields in
the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific
information about every record in the table.
What is column?
A column is a vertical entity in a table that contains all information
associated with a specific field in a table.
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are
used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints
are applied only to one column where as table level constraints are
applied to the whole table.
SQL Syntax:
SQL is followed by unique set of rules and guidelines called Syntax. This
tutorial gives you a quick start with SQL by listing all the basic SQL
Syntax:
All the SQL statements start with any of the keywords like SELECT,
INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the
statements end with a semicolon (;).
--11--
SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
--13--
--14--
SQL Statement
AND / OR
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE
or
ALTER TABLE table_name
DROP COLUMN column_name
SELECT column_name AS column_alias
FROM table_name
AS (alias)
or
SELECT column_name
FROM table_name AS table_alias
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE
DATABASE
CREATE TABLE
CREATE INDEX
--15--
SQL Statement
Syntax
ON table_name (column_name)
CREATE VIEW
DELETE
DROP DATABASE
DROP INDEX
DROP TABLE
EXISTS
GROUP BY
HAVING
IN
SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO table_name
VALUES (value1, value2, value3,....)
INSERT INTO
or
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
INNER JOIN
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LEFT JOIN
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
--16--
SQL Statement
Syntax
RIGHT JOIN
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FULL JOIN
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT
SELECT column_name(s)
FROM table_name
SELECT *
SELECT *
FROM table_name
SELECT DISTINCT
SELECT INTO
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP
TRUNCATE TABLE
UNION
UNION ALL
UPDATE
UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
--17--
SQL - Operators:
SQL Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then:
Show Examples
Operator
Description
Example
a + b will give
30
a - b will give
-10
a * b will give
200
b / a will give
2
Modulus - Divides left hand operand by right hand operand and returns remainder
b % a will give
0
Description
Example
Checks if the values of two operands are equal or not, if yes then condition becomes
true.
(a = b) is not
true.
!=
Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(a != b) is
true.
<>
Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(a <> b) is
true.
>
Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
(a > b) is not
true.
<
Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(a < b) is
true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
(a >= b) is
not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.
(a <= b) is
true.
!<
Checks if the value of left operand is not less than the value of right operand, if yes then
condition becomes true.
(a !< b) is
false.
!>
Checks if the value of left operand is not greater than the value of right operand, if yes
then condition becomes true.
(a !> b) is
true.
--18--
Description
ALL
The ALL operator is used to compare a value to all values in another value set.
AND
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
ANY
The ANY operator is used to compare a value to any applicable value in the list according to the condition.
BETWEEN
The BETWEEN operator is used to search for values that are within a set of values, given the minimum
value and the maximum value.
EXISTS
The EXISTS operator is used to search for the presence of a row in a specified table that meets certain
criteria.
IN
The IN operator is used to compare a value to a list of literal values that have been specified.
LIKE
The LIKE operator is used to compare a value to similar values using wildcard operators.
NOT
The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS,
NOT BETWEEN, NOT IN, etc. This is a negate operator.
OR
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IS NULL
UNIQUE
The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
STRUCTURED DATA
Accessing structured data with SQL is quite different from the full text search of
documents on the Web. Structured data in the relational model means data that can
be represented in tables -- rows and columns. Each row in a table represents a
different object, and the columns represent various "attributes" of the object. The
columns have names and integrity constraints that specify valid values.
Since the column values are named and are represented in a consistent format, you
can select rows very precisely, based on their contents. This is especially helpful in
dealing with numeric data. You can also join together data from different tables,
based on matching column values. You can do useful types of analysis, listing
objects that are in one table and missing (or present, or have specific attributes)
from a related table. You can extract from a large table precisely those rows of
interest, regrouping them and generating simple statistics on them.
--19--
ID
13
44
66
CITY
Phoenix
Denver
Caribou
STATE
AZ
CO
ME
LAT_N
33
40
47
LONG_W
112
105
68
CITY
Denver
STATE
LAT_N
CO
40
LONG_W
105
CITY
STATE
Phoenix
Denver
Caribou
AZ
CO
ME
CITY
STATE
Denver
Caribou
CO
ME
--21--
MONTH
TEMP_F
RAIN_I
13
57.4
.31
13
91.7
5.15
44
27.3
.18
44
74.8
2.11
66
6.7
2.1
66
65.8
4.52
--22--
ID
13
13
44
44
66
66
CITY
Phoenix
Phoenix
Denver
Denver
Caribou
Caribou
ST
AZ
AZ
CO
CO
ME
ME
LAT_N
33
33
40
40
47
47
LONG_W
112
112
105
105
68
68
ID
13
13
44
44
66
66
MONTH
1
7
1
7
1
7
TEMP_F RAIN_I
57.4
.31
91.7
5.15
27.3
.18
74.8
2.11
6.7
2.1
65.8
4.52
query to look at the table STATS, ordered by month and greatest rainfall,
with columns rearranged:
SELECT MONTH, ID, RAIN_I, TEMP_F
FROM STATS
ORDER BY MONTH, RAIN_I DESC;
MONTH
ID
RAIN_I
1 66
1 13
1 44
7 13
7 66
7 44
TEMP_F
2.1
.31
.18
5.15
4.52
2.11
6.7
57.4
27.3
91.7
65.8
74.8
MONTH
TEMP_F
1
7
1
RAIN_I
57.4
91.7
27.3
--23--
.32
5.16
.19
44
66
66
7
1
7
74.8
6.7
65.8
2.12
2.11
4.53
update one row, Denver's July temperature reading, to correct a data entry
error:
UPDATE STATS SET TEMP_F = 74.9
WHERE ID = 44
AND MONTH = 7;
and take a look:
SELECT * FROM STATS;
ID
MONTH
13
13
44
44
66
66
TEMP_F
1
7
1
7
1
7
RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8
--24--
.32
5.16
.19
2.12
2.11
4.53
MONTH
13
13
44
44
66
66
TEMP_F
1
7
1
7
1
7
RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8
.32
5.16
4.5
4.5
2.11
4.53
Oops! We meant to update just the July reading! Undo that update:
-- undoes only updates since the last COMMIT WORK.
ROLLBACK WORK;
and take a look:
SELECT * FROM STATS;
ID
MONTH
13
13
44
44
66
66
TEMP_F
1
7
1
7
1
7
RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8
--25--
.32
5.16
.19
2.12
2.11
4.53
MONTH
13
TEMP_F
1
RAIN_I
57.4
.32
delete July data and East Coast data from both tables:
-- note that we use longitude values from the related STATION table to determine
which STAT stations were east of 90 degrees.
DELETE FROM STATS
WHERE MONTH = 7
OR ID IN (SELECT ID FROM STATION
WHERE LONG_W < 90);
DELETE FROM STATION WHERE LONG_W < 90;
COMMIT WORK;
and take a look:
CITY
ST
Phoenix
Denver
LAT_N
AZ
CO
33
40
LONG_W
112
105
MONTH
1
1
TEMP_F
57.4
27.3
RAIN_I
.32
.19
--27--
#include<stdio.h>
#include<string.h>
EXEC SQL BEGIN DECLARE SECTION;
long station_id;
long mon;
float temp;
float rain;
char city_name[21];
long SQLCODE;
EXEC SQL END DECLARE SECTION;
main()
{
/* the CONNECT statement, if needed, goes here */
strcpy(city_name,"Denver");
EXEC SQL SELECT ID INTO :station_id
FROM STATION
WHERE CITY = :city_name;
if (SQLCODE == 100)
{
printf("There is no station for city %s\n",city_name);
exit(0);
}
printf("For the city %s, Station ID is %ld\n",city_name,station_id);
printf("And here is the weather data:\n");
EXEC SQL DECLARE XYZ CURSOR FOR
SELECT MONTH, TEMP_F, RAIN_I
FROM STATS
WHERE ID = :station_id
ORDER BY MONTH;
EXEC SQL OPEN XYZ;
while (SQLCODE != 100) {
EXEC SQL FETCH XYZ INTO :mon, :temp, :rain;
if (SQLCODE == 100)
printf("end of list\n");
else
printf("month = %ld, temperature = %f, rainfall =
%f\n",mon,temp,rain);
}
EXEC SQL CLOSE XYZ;
exit(0);
}
Execution log:
For the city Denver, Station ID is 44
And here is the weather data:
month = 1, temperature = 27.299999, rainfall = 0.180000
month = 7, temperature = 74.800003, rainfall = 2.110000
--28--
end of list
--29--
Oracle
What is Oracle
Oracle database is a relational database management system. It is known as Oracle database,
OracleDB or simply Oracle. It is produced and marketed by Oracle Corporation.
Oracle database is the first database designed for enterprise grid computing. The enterprise
grid computing provides the most flexible and cost effective way to manage information and
applications.
To create a table, you have to name that table and define its columns and datatype for each
column.
Syntax:
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
column_n datatype [ NULL | NOT NULL ]
);
--33--
Syntax:
1.
2.
3.
4.
1.
2.
3.
4.
5.
6.
7.
8.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
1.
2.
3.
4.
5.
6.
1.
PRICE
Syntax
1.
2.
3.
SELECT expressions
FROM tables
WHERE conditions;
Parameters
1) expressions: It specifies the columns or calculations that you want to retrieve.
2) tables:This parameter specifies the tables that you want to retrieve records from. There
must be at least one table within the FROM clause.
3) conditions: It specifies the conditions that must be followed for selection.
Select Example: select all fields
Let's take an example to select all fields from an already created table named customers
1.
2.
SELECT *
FROM customers;
output
1.
2.
3.
4.
5.
next prev
Oracle Insert Statement
In Oracle, INSERT statement is used to add a single record or multiple records into the
table.
Syntax: (Inserting a single record using the Values keyword):
1.
2.
3.
4.
1.
2.
3.
4.
5.
The values to assign to the columns in the table. So column1 would be assigned the value
of expression1, column2 would be assigned the value of expression2, and so on.
4) source_table:
The source table when inserting data from another table.
5) conditions:
The conditions that must be met for the records to be inserted.
Oracle Insert Example: By VALUE keyword
It is the simplest way to insert elements to a database by using VALUE keyword.
See this example:
Consider here the already created suppliers table. Add a new row where the value of
supplier_id is 23 and supplier_name is Flipkart.
1.
2.
3.
4.
1.
2.
3.
4.
5.
You can even check the number of rows that you want to insert by following statement:
1.
2.
3.
SELECT count(*)
FROM customers
WHERE age > 20;
Output:
Count(*)
INSERT ALL
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;
Parameters
1) table_name: it specifies the table in which you want to insert your records.
2) column1, column2, column_n: this specifies the columns in the table to insert values.
3) expr1, expr2, expr_n: this specifies the values to assign to the columns in the table.
Oracle INSERT ALL Example
This example specifies how to insert multiple records in one table. Here we insert three rows
into the "suppliers" table.
1.
2.
3.
4.
5.
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (20, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (21, 'Microsoft')
INTO suppliers (supplier_id, supplier_name) VALUES (22, 'Apple')
SELECT * FROM dual;
Output
3 row(s) inserted.
0.02 seconds
This is totally equivalent to the following three INSERT statements.
--39--
1.
2.
3.
1.
2.
3.
4.
5.
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (30, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (31, 'Microsoft')
INTO customers (age, name, address) VALUES (29, 'Luca Warsi', 'New York')
SELECT * FROM dual;
Output
3 row(s) inserted.
0.03 seconds
Here, total 3 rows are inserted, 2 rows are inserted into the suppliers table and one row into
the customers table.
Oracle UPDATE Statement
In Oracle, UPDATE statement is used to update the existing records in a table. You can
update a table in 2 ways.
Traditional Update table method
Syntax:
1.
2.
3.
4.
5.
6.
UPDATE table
SET column1 = expression1,
column2 = expression2,
...
column_n = expression_n
WHERE conditions;
Update Table by selecting rocords from another table
Syntax:
1.
2.
3.
UPDATE table1
SET column1 = (SELECT expression1
FROM table2
--40--
4.
5.
WHERE conditions)
WHERE conditions;
Parameters:
1) column1, column2, ... column_n:
It specifies the columns that you want to update.
2) expression1, expression2, ...expression_n:
This specifies the values to assign to the column1, column2, ?. column_n.
3) conditions:It specifies the conditions that must be fulfilled for execution of UPDATE
stateme.
Oracle Update Example: (Update single column)
1.
2.
3.
UPDATE suppliers
SET supplier_name = 'Kingfisher'
WHERE supplier_id = 2;
This example will update the supplier_name as "Kingfisher" where "supplier_id" is 2.
Oracle Update Example: (Update multiple columns)
The following example specifies how to update multiple columns in a table. In this example,
two columns supplier_name and supplier_address is updated by a single statement.
1.
2.
3.
4.
UPDATE suppliers
SET supplier_address = 'Agra',
supplier_name = 'Bata shoes'
WHERE supplier_id = 1;
Output:
1 row(s) updated.
0.06 seconds
Oracle Update Example: (By selecting records from another table)
1.
2.
3.
4.
5.
UPDATE customers
SET name = (SELECT supplier_name
FROM suppliers
WHERE suppliers.supplier_name = customers.name)
WHERE age < 25;
Output:
2 row(s) updated.
0.02 seconds
Here, the customers table is updated by fetching the data from "suppliers" table.
--41--
PL/SQL Programs
This appendix provides several PL/SQL programs to guide you in writing your
own. The sample programs illustrate several important PL/SQL concepts and
features.
This appendix discusses the following topics:
All the sample programs in this appendix and several others throughout this guide
are available online. So, they are preceded by the following comment:
-- available online in file '<filename>'
You can find the online files in the PL/SQL demo directory. For the location of the
directory, see the Oracle installation or user's guide for your system. Here is a list
of the files and their locations in this guide:
Filename
examp1
examp2
"Conditional Control"
examp3
"Iterative Control"
examp4
"Using Aliases"
examp7
examp8
examp5
Filename
examp6
examp11
"Example"
examp12
"Examples"
examp13
"Examples"
examp14
"Examples"
sample1
sample2
"Sample 2. Cursors"
sample3
"Sample 3. Scoping"
sample4
sample5
sample6
You run some samples interactively from SQL*Plus, others from Pro*C programs.
You can experiment with the samples from any Oracle account. However, the
Pro*C examples expect you to use the scott/tiger account.
Before trying the samples, you must create some database tables, then load the
tables with data. You do that by running two SQL*Plus
scripts, exampbld and examplod, which are supplied with PL/SQL. You can find
these scripts in the PL/SQL demo directory.
The first script builds the database tables processed by the sample programs. The
second script loads (or reloads) the database tables. To run the scripts, invoke
SQL*Plus, then issue the following commands:
SQL> START exampbld
--43--
...
SQL> START examplod
The following example uses a simple FOR loop to insert ten rows into a database
table. The values of a loop index, counter variable, and either of two character
strings are inserted. Which string is inserted depends on the value of the loop
index.
Input Table
Not applicable.
PL/SQL Block
-- available online in file 'sample1'
DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN
-- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Output Table
SQL> SELECT * FROM temp ORDER BY col1;
NUM_COL1 NUM_COL2
-------- -------1
100
2
200
3
300
4
400
5
500
6
600
7
700
8
800
9
900
10
1000
CHAR_COL
--------i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even
Sample 2. Cursors
The following example uses a cursor to select the five highest paid employees from
the emp table.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME
EMPNO
SAL
--44--
PL/SQL Block
-- available online in file 'sample2'
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC;
-- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal
NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total
*/
/* number of employees
*/
INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
COMMIT;
END LOOP;
CLOSE c1;
END;
Output Table
SQL> SELECT * FROM temp ORDER BY col1 DESC;
NUM_COL1 NUM_COL2
-------- -------5000
7839
3000
7902
3000
7788
2975
7566
2850
7698
CHAR_COL
-------KING
FORD
SCOTT
JONES
BLAKE
Sample 3. Scoping
The following example illustrates block structure and scope rules. An outer block
declares two variables named x and counter and loops four times. Inside this loop
is a sub-block that also declares a variable named x. The values inserted into
the temp table show that the two x's are indeed different.
Input Table
--45--
Not applicable.
PL/SQL Block
-- available online in file 'sample3'
DECLARE
x NUMBER := 0;
counter NUMBER := 0;
BEGIN
FOR i IN 1..4 LOOP
x := x + 1000;
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'in OUTER loop');
/* start an inner block */
DECLARE
x NUMBER := 0; -- this is a local version of x
BEGIN
FOR i IN 1..4 LOOP
x := x + 1; -- this increments the local x
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'inner loop');
END LOOP;
END;
END LOOP;
COMMIT;
END;
Output Table
SQL> SELECT * FROM temp ORDER BY col2;
NUM_COL1 NUM_COL2
-------- -------1000
1
1
2
2
3
3
4
4
5
2000
6
1
7
2
8
3
9
4
10
3000
11
1
12
2
13
3
14
4
15
4000
16
1
17
2
18
3
19
4
20
CHAR_COL
------------in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop
In the next example the accounts table is modified according to instructions stored
in the action table. Each row in the action table contains an account number, an
action to be taken (I, U, or D for insert, update, or delete), an amount by which to
update the account, and a time tag used to sequence the transactions.
--46--
--47--
Input Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- ------1
1000
2
2000
3
1500
4
6500
5
500
SQL> SELECT * FROM action ORDER BY time_tag;
ACCOUNT_ID
---------3
6
5
7
1
9
10
O NEW_VALUE STATUS
- ---------- -------------------u
599
i
20099
d
u
1599
i
399
d
x
TIME_TAG
--------18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
PL/SQL Block
-- available online in file 'sample4'
DECLARE
CURSOR c1 IS
SELECT account_id, oper_type, new_value FROM action
ORDER BY time_tag
FOR UPDATE OF status;
BEGIN
FOR acct IN c1 LOOP -- process each row one at a time
acct.oper_type := upper(acct.oper_type);
/*----------------------------------------*/
/* Process an UPDATE. If the account to */
/* be updated doesn't exist, create a new */
/* account.
*/
/*----------------------------------------*/
IF acct.oper_type = 'U' THEN
UPDATE accounts SET bal = acct.new_value
WHERE account_id = acct.account_id;
IF SQL%NOTFOUND THEN -- account didn't exist. Create it.
INSERT INTO accounts
VALUES (acct.account_id, acct.new_value);
UPDATE action SET status =
'Update: ID not found. Value inserted.'
WHERE CURRENT OF c1;
ELSE
UPDATE action SET status = 'Update: Success.'
WHERE CURRENT OF c1;
END IF;
/*--------------------------------------------*/
/* Process an INSERT. If the account already */
/* exists, do an update of the account
*/
/* instead.
*/
/*--------------------------------------------*/
--48--
Output Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -------1
399
2
2000
3
599
4
6500
6
20099
7
1599
SQL> SELECT * FROM action ORDER BY time_tag;
ACCOUNT_ID
NEW_VALUE STATUS
TIME_TAG
--49--
---------3
6
5
7
1
9
10
- ---------- --------------------u
599 Update: Success.
i
20099 Insert: Success.
d
Delete: Success.
u
1599 Update: ID not found.
Value inserted.
i
399 Insert: Acct exists.
Updated instead.
d
Delete: ID not found.
x
Invalid operation.
No action taken.
--------18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
The following example shows how you can embed PL/SQL in a high-level host
language such as C and demonstrates how a banking debit transaction might be
done.
Input Table
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -------1
1000
2
2000
3
1500
4
6500
5
500
--50--
/* null-terminate */
/* the string
*/
%s\n", status.arr);
--51--
printf("
Balance is now:
/* End of loop */
$%.2f\n", new_bal);
errprint:
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\n\n>>>>> Error during execution:\n");
printf("%s\n",sqlca.sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK RELEASE;
exit(1);
}
Interactive Session
Embedded PL/SQL Debit Transaction Demo
Trying to connect... connected.
** Debit which account number? (-1 to end) 1
What is the debit amount? 300
Status: Transaction completed.
Balance is now: $700.00
** Debit which account number? (-1 to end) 1
What is the debit amount? 900
Status: Insufficient funds.
Balance is now: $700.00
** Debit which account number? (-1 to end) 2
What is the debit amount? 500
Status: Transaction completed.
Balance is now: $1500.00
** Debit which account number? (-1 to end) 2
What is the debit amount? 100
Status: Transaction completed.
Balance is now: $1400.00
** Debit which account number? (-1 to end) 99
What is the debit amount? 100
Status:
Output Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -----1
700
2
1400
3
1500
4
6500
5
500
SQL> SELECT * FROM journal ORDER BY date_tag;
ACCOUNT_ID
----------
ACTION
--------------------
AMOUNT
---------
--52--
DATE_TAG
---------
1
2
2
Debit
Debit
Debit
300
500
100
28-NOV-88
28-NOV-88
28-NOV-88
This Pro*C program connects to Oracle, prompts the user for a department
number, then calls procedure get_employees, which is stored in package personnel.
The procedure declares three index-by tables as OUT formal parameters, then
fetches a batch of employee data into the index-by tables. The matching actual
parameters are host arrays.
When the procedure finishes, it automatically assigns all row values in the indexby tables to corresponding elements in the host arrays. The program calls the
procedure repeatedly, displaying each batch of employee data, until no more data is
found.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME
EMPNO
SAL
---------- --------- -------KING
7839
5000
SCOTT
7788
3000
FORD
7902
3000
JONES
7566
2975
BLAKE
7698
2850
CLARK
7782
2450
ALLEN
7499
1600
TURNER
7844
1500
MILLER
7934
1300
WARD
7521
1250
MARTIN
7654
1250
ADAMS
7876
1100
JAMES
7900
950
SMITH
7369
800
Stored Procedure
/* available online in file 'sample6' */
#include <stdio.h>
#include <string.h>
typedef char asciz;
EXEC SQL BEGIN DECLARE SECTION;
/* Define type for null-terminated strings. */
EXEC SQL TYPE asciz IS STRING(20);
asciz username[20];
asciz password[20];
int
dept_no;
/* which department to query */
char
emp_name[10][21];
char
job[10][21];
EXEC SQL VAR emp_name is STRING (21);
EXEC SQL VAR job is STRING (21);
float salary[10];
--53--
int
done_flag;
int
array_size;
int
num_ret;
/* number of rows returned */
int
SQLCODE;
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE sqlca;
int print_rows();
int sqlerror();
main()
{
int i;
/* Connect to Oracle. */
strcpy(username, "SCOTT");
strcpy(password, "TIGER");
EXEC SQL WHENEVER SQLERROR DO sqlerror();
EXEC SQL CONNECT :username IDENTIFIED BY :password;
printf("\nConnected to Oracle as user: %s\n\n", username);
printf("Enter department number: ");
scanf("%d", &dept_no);
fflush(stdin);
/* Print column headers. */
printf("\n\n");
printf("%-10.10s%-10.10s%s\n", "Employee", "Job", "Salary");
printf("%-10.10s%-10.10s%s\n", "--------", "---", "------");
/* Set the array size. */
array_size = 10;
done_flag = 0;
num_ret = 0;
/* Array fetch loop - ends when NOT FOUND becomes true. */
for (;;)
{
EXEC SQL EXECUTE
BEGIN personnel.get_employees
(:dept_no, :array_size, :num_ret, :done_flag,
:emp_name, :job, :salary);
END;
END-EXEC;
print_rows(num_ret);
if (done_flag)
break;
}
print_rows(n)
int n;
--54--
int i;
if (n == 0)
{
printf("No rows retrieved.\n");
return;
}
for (i = 0; i < n; i++)
printf("%10.10s%10.10s%6.2f\n",
emp_name[i], job[i], salary[i]);
}
sqlerror()
{
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\nOracle error detected:");
printf("\n% .70s \n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK WORK RELEASE;
exit(1);
}
Interactive Session
Connected to Oracle as user: SCOTT
Enter department number: 20
Employee
-------SMITH
JONES
SCOTT
ADAMS
FORD
Job
--CLERK
MANAGER
ANALYST
CLERK
ANALYST
Salary
-----800.00
2975.00
3000.00
1100.00
3000.00
--55--