0% found this document useful (0 votes)
4 views

ADB - Unit 1 - Chapter2

Bshdhsj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

ADB - Unit 1 - Chapter2

Bshdhsj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 1

Chapter 2
Fundamentals of PL/SQL

The PL/SQL Character Set

Type Characters

Letters A-Z, a-z

Digits 0-9

Symbols ~!@#$%&*()_-+=|[]{}:;"'<>,.?/^

Whitespace Tab, space, newline, carriage return

Lexical Units

PL/SQL is not case sensitive so you are free to use lower case letters or upper case letters except
within string and character literals. A line of PL/SQL text contains groups of characters known
as lexical units. It can be classified as follows:

o Delimeters
o Identifiers
o Literals
o Comments

The PL/SQL Identifiers


PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved
words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar
signs, underscores, and number signs and should not exceed 30 characters.
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to
represent a numeric value. You cannot use a reserved keyword as an identifier.
The PL/SQL Delimiters
A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL

Delimiter Description

+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)


/*, */ Multi-line comment delimiter (begin and end)

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL

The PL/SQL Comments


Program comments are explanatory statements that can be included in the PL/SQL code that
you write and helps anyone reading its source code. All programming languages allow some
form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any
comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with
the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World

PL/SQL procedure successfully completed.

Declaring a Constant
A constant is declared using the CONSTANT keyword. It requires an initial value and does
not allow that value to be changed. For example −
PI CONSTANT NUMBER := 3.141592654;
DECLARE
-- constant declaration
pi constant number := 3.141592654;
-- other declarations
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
-- processing
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
-- output
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53

Pl/SQL procedure successfully completed.

The PL/SQL Literals


A literal is an explicit numeric, character, string, or Boolean value not represented by an
identifier. For example, TRUE, 786, NULL, 'tutorialspoint' are all literals of type Boolean,
number, or string. PL/SQL, literals are case-sensitive. PL/SQL supports the following kinds of
literals −

 Numeric Literals
 Character Literals
 String Literals
 BOOLEAN Literals
 Date and Time Literals
The following table provides examples from all these categories of literal values.

S.No Literal Type & Example

Numeric Literals
1
050 78 -14 0 +32767

Character Literals
2
'A' '%' '9' ' ' 'z' '('

String Literals
'Hello, world!'
3
'Tutorials Point'
'19-NOV-12'

BOOLEAN Literals
4
TRUE, FALSE, and NULL.

Date and Time Literals


DATE '1978-12-25';
5
TIMESTAMP '2012-10-29 12:01:01';

Variable Declaration in PL/SQL


PL/SQL variables must be declared in the declaration section or in a package as a global
variable. When you declare a variable, PL/SQL allocates memory for the variable's value and
the storage location is identified by the variable name.
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data
type or any user defined data type which we already have discussed in the last chapter. Some
valid variable declarations along with their definition are shown below −
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
When you provide a size, scale or precision limit with the data type, it is called a constrained
declaration. Constrained declarations require less memory than unconstrained declarations.
For example −
sales number(10, 2);
name varchar2(25);
address varchar2(100);

Initializing Variables in PL/SQL


Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to
initialize a variable with a value other than the NULL value, you can do so during the
declaration, using either of the following −
 The DEFAULT keyword
 The assignment operator

For example −
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';

You can also specify that a variable should not have a NULL value using the NOT
NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an initial
value for that variable.
It is a good programming practice to initialize variables properly otherwise, sometimes
programs would produce unexpected results. Try the following example which makes use of
various types of variables −
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
When the above code is executed, it produces the following result −
Value of c: 30
Value of f: 23.333333333333333333

PL/SQL procedure successfully completed.


Expressions
An SQL expression is a combination of one or more values, operators and SQL functions that
are all evaluated to a value. These SQL EXPRESSIONs are like formulae and they are written
in query language. You can also use them to query the database for a specific set of data.
Expressions are used in WHERE clause of an SQL query. As you might have already known,
a WHERE clause specifies a condition that needs to be satisfied for the purpose of filtering
records from a database table. This condition is comprised of either single or multiple
expressions. These expressions are further classified into three types −

 Boolean Expressions
 Numeric Expressions
 Date and time Expressions

Syntax
Consider the basic syntax of the SELECT statement containing expressions as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION|EXPRESSION];

Boolean Expressions
SQL Boolean Expressions are SQL expressions that only return Boolean Datatype as a result.
These expressions can be of two types −

 Boolean Expressions that check for equality of two values using SQL comparison
operators. Here, equality of these values is a condition.
 Boolean Expressions can also contain one value paired with an SQL logical operator.
In this case, the logic specified acts like a condition.
They return either TRUE, FALSE or UNKNOWN as the result. If the condition is met, these
expressions return TRUE; and FALSE otherwise. UNKNOWN is returned when operands in
the expression are NULL values.

Syntax
Following is the syntax −
SELECT column1, column2, columnN
FROM table_name
WHERE BOOLEAN EXPRESSION;
Example
Consider the CUSTOMERS table having the following records −
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
7 rows in set (0.00 sec)
The following query is a simple example showing the usage of an SQL Boolean Expression −
SELECT * FROM CUSTOMERS WHERE SALARY = 10000;

Output
The output will be displayed as −
+----+-------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+----------+
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+-------+-----+---------+----------+
1 row in set (0.00 sec)
Numeric Expression
Numeric expressions are comprised of two operands and an SQL Arithmetic Operator. These
expressions are used to perform any mathematical operation in any query. Hence, the operands
must always be numerals and the return value will always be a number as well.
Syntax
Following is the syntax −
SELECT numerical_expression as OPERATION_NAME
FROM table_name
WHERE NUMERICAL EXPRESSION ;
Here, the numerical_expression is used for a mathematical expression or any formula.
Example
Following is a simple example showing the usage of SQL Numeric Expressions −
SELECT (15 + 6) AS ADDITION
Output
The output table is retrieved as −
+----------+
| ADDITION |
+----------+
| 21 |
+----------+
1 row in set (0.00 sec)
Example
There are several built-in functions like avg(), sum(), count(), etc., to perform what is known
as the aggregate data calculations against a table or a specific table column.
SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS;
Output
The output is displayed as follows −
+---------+
| RECORDS |
+---------+
| 7|
+---------+
1 row in set (0.00 sec)
Date Expressions
Date Expressions are used to compare date related values with current system date and time
values.
For instance, in a manufacturing company, items manufactured per year can be segregated by
using date expressions in a WHERE clause. Counting from the first day of an year to the last
day, the count of each item will be retrieved; once the required information is gathered, the
company can use this information for their own purposes.
Syntax
Following is the syntax −
SELECT column_name(s)
FROM table_name
WHERE DATE EXPRESSION ;

Example
In this example we are trying to simply retrieve the current timestamp of the system using
CURRENT_TIMESTAMP.
SELECT CURRENT_TIMESTAMP;
Output
The output table is displayed as −
+---------------------+
| Current_Timestamp |
+---------------------+
| 2009-11-12 06:40:23 |
+---------------------+
1 row in set (0.00 sec)

Example
Following example is using WHERE clause to retrieve the Date values less than 1st June, 2008
from our ORDERS table shown below.
+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
SELECT DATE FROM ORDERS WHERE DATE < '2008/06/01';

Output
The output table is displayed as −
+-------------------------+
| DATE |
+-------------------------+
| 2008-05-20 00:00:00 |
+-------------------------+
1 row in set (0.00 sec)

Error-Reporting Functions
An exception is an error condition during a program execution. PL/SQL supports programmers
to catch such conditions using EXCEPTION block in the program and an appropriate action
is taken against the error condition. There are two types of exceptions −

 System-defined exceptions
 User-defined exceptions
Syntax for Exception Handling
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!

PL/SQL procedure successfully completed.


The above program displays the name and address of a customer whose ID is given. Since there
is no customer with ID value 8 in our database, the program raises the run-time
exception NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined exception.
You can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the
user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Data Types

Numeric
1
Numeric values on which arithmetic operations are performed.

Character
2
Alphanumeric values that represent single characters or strings of characters.

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.

You might also like