Documente Academic
Documente Profesional
Documente Cultură
Srecko Howard
Glen Van Der Vyver
Page 75
Information Systems Developers Handbook
The idea, thought of as revolutionary not many years ago, that data could be
independent of applications, heralded the rapid evolution of the database. Today, an
overwhelming majority of applications are database-driven. The database is a key
corporate asset, often constituting the margin between success and failure.
As the use of databases became more pervasive, the need arose to develop a
language that could extract and manipulate data in the database. Hence Structured
Query Language (SQL) was born. This language works in a fundamentally different
way to languages such as C++ or COBOL, which are often referred to as
‘procedural’ programming languages. Code written in these languages implies an
end result by explicitly defining the means or procedures to get there. In contrast,
SQL explicitly defines the end result, leaving it up to the data base management
system (DBMS) to determine the method of obtaining the data. SQL is, therefore, a
relatively simple language with a limited syntax. Although many standards exist for
the structure and mathematical underpinnings of SQL, commercial programming
standards have been uncommon. The only widely applied standard for many years
was that a SQL statement must be spread over multiple lines.
Databases have changed dramatically in recent years. The database is no longer just
the repository of raw information. Today, the knowledge of the business, its rules
and procedures, is often stored in the database. Oracle Corporation has developed
PL/SQL, a procedural extension of the base SQL language, to cater for the
increasingly sophisticated demands business places on the database. The PL/SQL
language offers far more execution potential than the simple update, select, insert
and delete statements of SQL. It allows for things such as modularity, variable
declaration, loops and advanced error handling. The PL/SQL language is
specifically designed to interface optimally with the database and to seamlessly
handle the logic and business rule enforcement of database applications. Although it
is a much simpler language than, for instance C++, it has all the common logical
constructs required of a programming language. It also has many attributes other
languages do not have — such as modularisation of code blocks.
The PL/SQL code used to interface with the Oracle database may be stored in
applications programs or directly within the Oracle database, making PL/SQL the
only programming language that interfaces with the Oracle database natively and
within the database environment.
SQL has been accepted as the American standard by ANSI and as the international
standard by ISO. The most current ANSI standard is SQL-92, although new SQL3
and SQL4 standards are in the pipeline. These are likely to extend the capabilities of
SQL-92, which sets the minimum standard for a compliant database. It has become
rather the custom for individual vendors to offer distinct flavours of SQL. These
may involve the extension of capabilities on the base standard, or be as minor as a
subtle difference in syntax. The programmer must approach each different version
of SQL with caution, as it will often happen that a statement, which works perfectly
in one particular version of SQL, will fail in another.
Page 76
Chapter 7 Oracle Database Programming
Standards for PL/SQL have developed slowly. Most companies using Oracle have
PL/SQL programs running into many thousands of lines, but there is a wide range
of standards. Inevitably, the situation is slowly changing. Of particular importance
is the fact that companies often store a large volume of PL/SQL dynamically within
the database in the form of packages, stored procedures, triggers and so on. It is
very expensive to store sloppy, non-optimised code within the database.
Due to the relative simplicity of PL/SQL, many argue that it requires a smaller and
less complex set of standards than many other languages. Whether this is accurate
or not, these standards are likely to be applied in a wider variety of contexts than
most languages, for example, standalone programs, stored procedures, database
triggers, and within Developer 2000/Oracle Reports. The same set of standards is
required by the Department of Information Systems to be applied in all contexts.
7.1.1 Tables
Table names must clearly and unambiguously describe the table. The name chosen
must reflect the contents of the table. For example, if the table contains records of
employee details the appropriate name might be EMPLOYEES. Note that the table
name is in the plural form. This signifies that it is a collection of records, as
opposed to a single individual entity (employee). Avoid using abbreviated names,
unless they are clear and well understood. Interception or Associative entities
(tables which are involved in many to many relationships) may be named via a
concatenation of the names of both entities if a simple description is not available.
7.1.2 Columns
A column name must describe the contents of the column and must be consistent
across all tables in the application. Adherence to this standard will ensure that
programming and documentation tasks are greatly simplified, as is the process of
understanding program code.
Page 77
Information Systems Developers Handbook
7.1.3 Variables
Make variable names as descriptive as possible and avoid using one or two
character names. This would only be appropriate as a counter for a simple loop
where a numeric value is involved. Ensure that variable names clearly distinguish
local variables from table columns. One common error, that causes much confusion,
occurs when a local variable is given the same name as a related table column.
Therefore, use a ‘v’ to signify a variable.
declare
vCounter NUMBER;
begin
loop
vCounter := vCounter + 1;
end loop;
end;
Where appropriate, use multiple words with the first letter of each word capitalised
to make the variable meaning clear.
declare
vNotFinished BOOLEAN;
vTotalRecords NUMBER;
begin
vMoreRecords := TRUE;
vTotalRecords := 0;
Page 78
Chapter 7 Oracle Database Programming
declare
Cursor vEmployeeCursor is
SELECT *
FROM Employees;
vEmployeeRec vEmployeeCursor%ROWTYPE;
begin
open vEmployeeCursor;
fetch vEmployeeCursor Into vEmployeeRec;
ProcessRecord( vEmployeeRec );
close vEmployeeCursor;
end;
7.1.6 Parameters
Formal parameters in functions and procedures must follow the same standards as
specified for variables. The variable operation type ‘in’, ‘out’ or ‘inout’ must be
specified when defining formal parameters. Use the function type if only one value
needs to be returned. It is considered poor practice to use the procedure variable
mechanism to modify parameters. For a more detailed discussion on the use of
procedures and functions refer to section 7.7 Functional Decomposition, in this
chapter.
7.1.7 Forms
The Oracle form wizard, by default, creates forms with the same name as the base
table. It is possible to create a form not based on any table and then assign a table
to it through the object browser. Forms that are not based on any table must have
the prefix ‘frm’ in their name. All forms must maintain the same naming
convention, that is, using the ‘frm’ prefix.
Page 79
Information Systems Developers Handbook
7.1.8 Blocks
Blocks based on tables will inherit the table name. Control blocks, that is, blocks
not based on any table, must have the ‘blk’ prefix to identify the object as a block.
Refer to your textbook for a more detailed discussion on use of blocks and forms
programming.
7.1.9 Fields
A field that represents a column in a table must have the same name as the column.
Fields which are not directly related to columns in a table must be prefixed with a
clear type indicator. For example, text input fields must be indicated with ‘txt’
prefix, combo boxes with ‘cmb’, text fields with ‘txt’ and so on. For other field
types, choose an appropriate and meaningful extension. Refer to Oracle help files
for a more detailed description of objects available.
This section will not cover the syntax of DDL statements (which is not complex) in
great detail. Rather, it will provide pointers about the correct usage of DDL
statements and the basic structure of the most important statements.
Databases must not be created ‘on the fly’. All DDL statements must
be stored in a script file, which is used to create the database. The
commands for any subsequent modification to the database must be
added to the script file, along with appropriate documentation. Do not
rely absolutely on database exports for recovery.
Page 80
Chapter 7 Oracle Database Programming
7.2.2 Create
Creating tables and related objects is the first task of database development.
Physically, a database is a set of files resident on a disk. Logically, a database
comprises user accounts identified by username and password. Each user account
owns a variety of database objects, for example, tables. Each table name must be
unique for that user. Indeed, for each object type, each individual object must have
a unique name for a particular user.
Table
A table stores the data in a relational database. A table name and a name, data type
and size for each field (column) must be specified. A primary key is usually also
specified at the time of creation, often in conjunction with other constraints. The
specification of constraints, triggers and other server-side mechanisms will depend
upon the system model driving development (eg, client-server), business rules and a
variety of other factors.
View
A view is a logical table. It is based on a normal select statement (a query) which
may involve one or more tables. A view DOES NOT store data and it may present
data in a different format and/or sequence than the underlying tables.
Sequence
A sequence is a number drawn from a sequential list maintained by Oracle and
generated automatically. It is often used to create artificial or surrogate keys when
no column in a table can guarantee uniqueness.
Page 81
Information Systems Developers Handbook
Index
Indexes are used to speed up data retrieval. They facilitate the retrieval of specific
rows from a table, in optimal circumstances removing the necessity for a full table
scan and minimising the number of row hits. It is important to note that an index
does not guarantee improved performance on a select statement and may actually
retard the overall performance of the system. The design of indexes is an important
task of the DBA.
Alter
The alter command is used to change and maintain database objects, primarily
tables, views, sequences and indexes. There is a wide variety of alter statements,
however, it is not intended to cover their specific syntax here. Note, however, that
an alter statement may work in particular circumstances and fail in others. Also,
changing the structure of database objects could result in initiating fundamental
changes in data interrelationships, as well as influencing business rules.
Drop
The drop command is used to remove objects (tables, views, indexes, sequences,
etc) from the data dictionary.
Page 82
Chapter 7 Oracle Database Programming
7.3.1 Select
The SELECT statement within PL/SQL allows selection of a single row of
information to be stored in a local variable. Below is an example of mixed PL/SQL
and SQL that retrieves and processes a single record. The select statement will
retrieve only one record into the variable ‘vEmp’ assuming that the database has
been normalised to ensure that the ‘employeeID’ field stores unique values. If
the search criteria were to retrieve more than one record, it would then be necessary
to use cursors to process each record. Please refer to section 7.1.4 Cursors and
Records in this chapter, and your textbook, for further information.
Declare
vEmpRec SCOTT.Salary%ROWTYPE;
begin
SELECT *
INTO vEmpRec
FROM SCOTT.Salary
WHERE employeeID = 1313;
--
--process the record here
--
end;
Page 83
Information Systems Developers Handbook
7.3.2 Insert
The INSERT statement can be used in PL/SQL to achieve the same result as in
SQL, that is, insert one or more records into a table. The syntax is the same as with
a plain SQL statement. Refer to the snippet of code below for the preferred
formatting style.
declare
vEmpRec SCOTT.Salary%TYPE;
begin
SELECT *
INTO vEmpRec
FROM SCOTT.Salary
WHERE employeeID = 1313;
7.3.3 Update
The UPDATE statement can be used in PL/SQL to update one or more records in a
table. The syntax is the same as with a standard SQL statement. Below is a simple
example of an update statement. Note that the employee whose ID is 1313 in this
instance will have their salary increased by 20 percent. The table with the salary
information is named ‘Salary’ and owned by user ‘SCOTT’.
begin
UPDATE SCOTT.Salary
SET Sal = Sal * 1.20;
WHERE employeeID = 1313;
end;
7.3.4 Delete
The DELETE statement can be used in PL/SQL to delete one or more records from
a table. The syntax is the same as with a standard SQL statement. In the example
below the delete statement is applied to a single record. The employee with the
employee ID of 1313 will be deleted from the ‘Salary’ table owned by user
‘SCOTT’.
begin
Page 84
Chapter 7 Oracle Database Programming
Page 85
Information Systems Developers Handbook
Indenting is mandatory for readability and understanding. All blocks, selection and
repetition constructs must have indented statements. Avoid using tabs for
indentation unless your editor converts the tabs to spaces. Having tabs in your
document may cause your source code to be misaligned when imported into a
different editor. Generally speaking, programmers use between two to six spaces
for indentation. Again, there is no set requirement covering the number of spaces
used for indenting, however, indenting must be consistent throughout the whole
document.
Declare
--------;
begin
--------;
--------;
--------;
exception
--------;
--------;
end;
Page 86
Chapter 7 Oracle Database Programming
When using nested blocks the outer block must have an exception section to catch
any exceptions not handled by the inner blocks. Exceptions in the inner blocks
would be dependent on the logic used in the code.
Nested blocks can easily obscure the logic and make the code hard to maintain.
Using appropriate indentation can greatly aid in readability and understanding of
the code. In all programming units, appropriate indentation and setting out of code
is required. Skeleton code below demonstrates an indentation style for use in
nested blocks.
declare
--------;
begin
--------;
--------;
declare
--------;
begin
--------;
--------;
exception
--------;
--------;
end;
--------;
exception
--------;
--------;
end;
Page 87
Information Systems Developers Handbook
Two styles of comments are available in PL/SQL, namely, single line comments
and multiple line comments. Single line comments can be used to have an entire
line ignored by the compiler by placing a double hyphen (--) at the start of the line.
This particular comment marker can also be used to add a comment to the end of a
line or to temporarily disable a line of code as shown in the code snippet below.
The other form of comment is the multiple line comment. It is started with the
slash-asterisk (/*) opening sequence and everything after the slash asterisk is treated
as a comment until the closing asterisk-slash (*/) sequence. When using multi line
comments it is essential to terminate the comment section with a (*/). Failing to do
so could result in misleading errors from the PL/SQL parser.
Page 88
Chapter 7 Oracle Database Programming
declare
vName Students.Name%TYPE;
vAge NUMBER;
vPostCode CHAR(4);
vMarried BOOLEAN := FALSE;
vToday := SYSDATE;
begin
end;
Page 89
Information Systems Developers Handbook
declare
vName Students.Name%TYPE;
vAge NUMBER;
begin
SELECT name, age
INTO vName, vAge
FROM Students
WHERE StudentNumber = 13;
exception
when No_Data_Found then
message (‘Student Not Found’);
end;
Please refer to the discussion on Cursors and Records, in section 7.1.4 of this
chapter.
declare
vStudentRec Students%ROWTYPE;
-- vStudentRec has all the filed in Students table
begin
SELECT *
INTO vStudentRec
FROM Students
WHERE StudentNumber = 13;
exception
when No_Data_Found then
Page 90
Chapter 7 Oracle Database Programming
subroutines to be effective they must be simple and well defined. They must also
provide only one service and be clear in their purpose. Oracle uses procedures and
functions as the mechanism for functional decomposition. In this chapter the
primary focus is on procedures and functions available as part of the application,
and not those stored in the database.
7.8 Procedures
Subroutines, which provide service but do not return a value, are known as
procedures. Information may be passed between the called subroutine and the
calling routine using parameters. When values are passed into the subroutine they
must be identified with the type of operation allowed on them. The modifiers may
be of the type ‘in’, ‘out’ or ‘inout’. For a more detailed description of
parameter modifiers please refer to the PL/SQL section of your textbook.
7.9 Functions
The last area to be considered in this chapter is that of functions. Functions, like
procedures, perform a simple and distinct service. Unlike procedures a function
must return a value at the end of its execution. The value passed back is the result
of performing the function execution. As with the procedure, values passed into the
subroutine must be identified with the type of operation allowed in them. The
modifiers may be of the type ‘in’, ‘out’ or ‘inout’. For a more detailed
description of parameter modifiers please refer to the PL/SQL section of your
textbook.
Page 91
Information Systems Developers Handbook
Page 92