PL SQL Notes Examples
PL SQL Notes Examples
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.A
view can contain all rows of a table or select rows from a table. A view can be created from
one or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables that allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from
a single table, multiple tables or another view. To create a view, a user must have the
appropriate system privilege according to the specific implementation.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them
in a normal SQL SELECT query.
Example:
SQL > CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM
CUSTOMERS;
SQL> SELECT * FROM CUSTOMERS_VIEW;
The WITH CHECK OPTION:
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the
WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s)
in the view definition. If they do not satisfy the condition(s), the UPDATE or INSERT
returns an error. The following code block has an example of creating same view
CUSTOMERS_VIEW with the WITH CHECK OPTION.
Example:
SQL>CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM
CUSTOMERS WHERE age IS NOT NULL WITH CHECK OPTION;
1
The WITH CHECK OPTION in this case should deny the entry of any NULL values
in the view's AGE column, because the view is defined by data that does not have a NULL
value in the AGE column.
Updating a View
A view can be updated under certain conditions which are given below −
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The
following code block has an example to update the age of Bhargavi.
Example:
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Bhargavi';
This would ultimately update the base table CUSTOMERS and the same would reflect in the
view itself.
Inserting Rows into a View:
Rows of data can be inserted into a view. The same rules that apply to the UPDATE
command also apply to the INSERT command. Here, we cannot insert rows in the
CUSTOMERS_VIEW because we have not included all the NOT NULL columns in this
view, otherwise you can insert rows in a view in a similar way as you insert them in a table.
Deleting Rows from a View:
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command. Following is an example to delete a
record having AGE = 22.
2
Example:
SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the same would
reflect in the view itself.
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
Syntax:
DROP VIEW view_name;
Example:
DROP VIEW CUSTOMERS_VIEW;
3
Views
1.Create a view that displays the employee id, name and salary of employees who belong to
10th department.
Query:
Create view emp_view as select employee_id,last_name,salary from employees where
department_id=10;
2.Create a view with read only option that displays the employee name and their department
name
Query:
create view emp_dept as select employee_id,last_name,department_id from employees with
read only constraint emp_dept_readonly;
4
3. Display all the views generated.
Query:
select view_name from user_views;
Output:
5
Output:
Drop a view.
Query: drop view my_view;
Output:
6
Introduction to PL/SQL
Delimiters:
Delimiters are symbols or compound symbols, which have a special meaning to
PL/SQL. You will recognize many of them as operators from SQL.
1. Simple Symbols:These consist of one character.
+ addition operator
- subtraction operator
/ division operator
= relational operator
> relational operator
< relational operator
( expression or list delimiter
) expression or list delimiter
; statement terminator
% attribute indicator
, item separator
. component selector
@ remote access indicator
‘ character string delimiter
: host variable indicator
Note: Spaces are not allowed between the two component characters of these compound
symbols.
Literals:
7
A literal is an explicit numeric, string, or Boolean value not represented by an
identifier. The numeric literal 147 and the Boolean literal FALSE are examples.
1. Numeric Literals
Two kinds of numeric literals can be used in arithmetic expressions: integers and real
literals.
a) An integer literal: (is an optionally signed whole number without a decimal point)
Ex:
40 9 -14 0 32767
b) A real literal:
Ex: 6.6667 0.0 -12.0 3.14159 +8300.00 0.5 25.
Numeric literals cannot contain dollar signs or commas, both can be written using
scientific notation. Simply suffix the number with an E (or e) followed by an optionally
signed integer.
Ex: 2E5 1.0E-7 3.14159e -1E38 -9.5e-
0 3
2. Character Literals
A character literal is an individual character enclosed by single quotes. The characters
can be Letters, numerals, spaces, and special symbols.
Ex: ‘Z’ ‘%’ ‘7’ ‘ ‘ ‘ ‘ ‘z’ ‘(‘
3. String Literals
A character value can be represented by an identifier or explicitly written as a string
literal, which is a sequence zero or more characters enclosed by single quotes.
Ex:‘HELLO, WORLD!’ ‘XYZ Corporation’ ‘ 10 -NOV-91’
‘He said “Life is like licking honey from a thorn.”’
‘$1,000,000’
4. Boolean Literals
Boolean literals are the predefined values TRUE, FALSE, and NULL (which stand for
a missing, unknown, or inapplicable value). Boolean literals are values, not strings. For
example, TRUE is no less a value than the number 25.
Comments:
PL/SQL supports two comment styles: Single –Line and Multi-Line.
1. Single-Line
8
Single-line comments begin with a double hyphen(--) anywhere on a line and extend
to the end of the line.
Ex:---Welcome to vnr
SELECT PERCENTAGE FROM STUDENT --get current percentage
2. Multi – line
Multi –line comments begin with a slash –asterisk (/*), end with an asterisk-slash
(*/), and can span multiple lines.
Ex:
BEGIN
…..
/* Compute a 15% bonus for top-rated employees. */
IF rating > 90 THEN
Bonus := salary * 0.15 /* bonus is based on salary */
ELSE
Bonus :-0;
END If;
...
Area := pi * radius**2;
END;
BlockTypes PL/SQL Structure:
A block lets the user to group logically related declarations and statements. The
declarations are local to the block and cease to exist when the block completes.
A PL/SQL has three parts:
Declarative part - for declaring variables and objects
Executable part - for manipulation of data in the database
through the declared variables and objects.
Exception handling part - for handling exceptions that are raised during
the execution.
9
Anonymous Procedure Function
FLOAT VARCHAR2
INT DATE
INTEGER
BOOLEAN
1. Scalar Datatypes :
They hold a single value
Have no internal components
Main data types are those that correspond to column types in
oracle server tables
Supports Boolean variables.
2.Composite Data types: A composite types has internal components that can be
manipulated individually. Composite data types (Also known as collections ) are of TABLE,
RECORD, NESTED.
Records allow groups of fields to be defined and manipulated in PL/SQL Blocks.
<variable><Tablename>%rowtype; rec emp%rowtype;
Variables and Constants:
PL/SQL allows declaration of variables and constants.
10
Types of variables:
PL/SQL Variables: All PL/SQL variables have a datatype, which specifies storage
formats, constants, and valid range of values. PL/SQL supports four data type categories---
1. Scalar
2. Composite
Non PL/SQL variables:They include host language variables declared in pre-compiled
programs, screen fields in Forms applications, and SQL*Plus or iSQL*Plus host variables.
Declaring Variables
JoinDate DATE ;
Emp_count SMALLINT := 0 ;
acct_id VARCHAR2(5) NOT NULL := ‘AEOO1’ ;
pi CONSTANT REAL := 3.14159 ;
radius REAL := 1 ;
area REAL := pi * radius ** 2 ;
valid BOOLEAN DEFAULT FALSE ;
tax SMALLINT DEFAULT 92;
Control Structures:
Three basic control structures are
Sequence
Selection
Iteration
1. Sequence structure simply executes a sequence of statements in the order in which they
occur.
2. Selection structure test a condition, then executes the statements of that block.
3. Iterative structure executes a sequence of statements repeatedly as long as a condition
holds true.
1. Conditional (Selection) control:
i) IF statements
a) IF – THEN
IF condition THEN
Sequence of statements;
END IF;
Example:
11
DECLARE
Eng number;
Maths number;
Science nuber;
Total number;
Per number;
BEGIN
Eng:=&englishmarks;
Maths:=&mathsmarks;
Science:=sciencemarks
Total:=eng+maths+science;
Per:=total/3;
If(per>=75)then
Dbms_output.put_line(‘Distinction’);
Elsif(per>-60and per<75) then
Dbms_output.put_line(‘Credit’);
Elsif(per>=40 and per<60)then
Dbms_output.put_line(‘Pass’);
Else
Dbms_output.put_line(‘Fail’);
End if;
End if;
End if;
End;
b) IF – THEN – ELSE
IF condition THEN
Sequence of statements1;
ELSE
Sequence of statements2;
END IF;
c) IF – THEN – ELSIF
IF condition1 THEN
Sequence of statements1;
ELSIF condition2 THEN
12
Sequence of statements2;
ELSE
Sequence of statements3;
END IF;
Example:
Declare
Eng number;
Maths number;
Science number;
Total number;
Per number;
Begin
Eng:=&englishmarks;
Maths:=&mathsmarks;
Science:=&sciencemarks
Total:=eng+maths+science;
Per:=total/3;
If(per>=75)then
Dbms_output.put_line(‘Distinction’);
Elsif(per>-60and per<75) then
Dbms_output.put_line(‘Credit’);
Elsif(per>=40 and per<60)then
Dbms_output.put_line(‘Pass’);
Else
Dbms_output.put_line(‘Fail’);
End if;
End;
If cond then
If cond then
Statements;
Else
Statements;
End if;
Else
13
Statements;
End if;
d) Nested IF - IF statement can be nested in another IF statement.
2. Iterative (loops) Control:
i) LOOP- allows the user to execute a sequence of statements multiple times.
LOOP
Sequence of statements;
Exit when condition;
END LOOP;
Ex: Declare
X number:=2;
Begin
Loop
Dbms_output_line(x);
X:=X+2;
Exit when X=22;
End loop;
End;
ii)FOR
It allows the user to specify a range of integers, then executes a sequence of
statements once for each integer in the range.
FOR <var> IN <lower>. .<upper> LOOP
Sequence of statements;
END LOOP;
iii) WHILE
It associates a condition with a sequence of statements.
WHILE condition LOOP
Sequence of statements;
END LOOP;
Composite Datatypes:
1. PL/SQL Records
A record is a variable that may contain a collection of separate values, each
individually addressable.
14
Syntax:
TYPE <record_name> IS RECORD
( <field_name> { datatype | variable%TYPE | table.column%TYPE |
table%ROWTYPE },
<field_name> { datatype | variable%TYPE | table.column%TYPE |
table%ROWTYPE },
…….
);
Ex:
TYPE emp_rec IS RECORD
(
num emp.empno%TYPE not null := 7788,
name emp.ename%TYPE,
salary number(10,2)
);
Declaring variables of RECORD composite type
e1 emp_rec;
Storing data into a record variable
select empno, ename, sal into e1 from emp where empno = 7654;
Referring individual fields in a record
record_name.field_name;
dbms_output.put_line( e1.num );
Nested Record
A record contains one of its members, as a variable of another record.
Accessing the members of inner record
record_name . member_name . field_name
Ex:-
declare
TYPE empdept is record
(
dno dept.deptno%TYPE,
dname dept.dname%TYPE,
eno emp.empno%TYPE,
ename emp.ename%TYPE,
15
salary emp.sal%TYPE
);
ed1 empdept;
begin
select emp.deptno, dname, empno, ename, sal into ed1 from emp, dept
where emp.deptno = dept.deptno and empno = 7788;
ed1.salary := ed1.salary + ed1.salary * 0.1;
dbms_output.put_line( ‘ Deptno : ‘ || ed1.dno );
dbms_output.put_line( ‘ Dname : ‘ || ed1.dname );
dbms_output.put_line( ‘ Empno : ‘ || ed1.eno );
dbms_output.put_line( ‘ Ename : ‘ || ed1.ename );
dbms_output.put_line( ‘ Salary : ‘ || ed1.salary );
end;
1. Write a PL/SQL code to retrieve the employee name, join date and designation from
employee database of an employee whose number is input by the user.
Program:
/*Employee details*/
DECLARE
v_name varchar2(25);
v_joindate date;
v_dsgn employees.job_id%type;
BEGIN
END;
16
Output:
Program:
/*Calculate Tax*/
DECLARE
v_sal number(8);
v_tax number(8,3);
v_name varchar2(25);
BEGIN
if v_sal<10000 then
v_tax:=v_sal*0.1;
v_tax:=v_sal*0.2;
else
v_tax:=v_sal*0.3;
END IF;
DBMS_OUTPUT.PUT_LINE('Name:'||v_name||' Salary:'||v_sal||'Tax:'||v_tax);
END;
Output:
17
Write PL/SQL program to
1. Find the Sum and Product of two numbers by taking numbers from user and also
choice if ch=1 find sum or else product using if else.
2. Sum of first ‘n’ natural numbers using while loop.
3. Numbers in reverse order using loop and exit.
4. Find the maximum salary in a department given by the user.
18