PLSQL
PLSQL
A foreign key is a way to enforce referential integrity within your Oracle database. The referenced table is
called the parent table while the table with the foreign key is called the child table. The foreign key in the
child table will generally reference a primary key in the parent table.
Cascade DELETE
A foreign key with cascade delete means that if a record in the parent table is deleted, then the
corresponding records in the child table with automatically be deleted. This is called a cascade delete in
Oracle.
Create table emp
(empid number not null,
Ename varchar2(50) not null,
Deptno number not null,
Constraint deptno_pk PRIMARY KEY (deptno)
);
Create table dept
(
Deptno number,
Deptname varchar2(50),
Constraint fk_deptno
FOREIGN KEY(deptno)
REFERENCES EMP(DEPTNO)
ON DELETE CASCADE
);
SAVEPOINT
Use the SAVEPOINTstatement to identify a point in a transaction to which you can roll back
later.
UPDATEemployees
SETsalary=7000
WHERElast_name='Banda';
SAVEPOINTa;
UPDATEemployees
SETsalary=12000
WHERElast_name='Greene';
SAVEPOINTb;
ROLLBACKTOSAVEPOINTa;
COMMIT;
What is View :View is database object which is usually providing the authority of security levels. View doesnt store
data. View is virtual table. it is created by a query joining one or more tables.
Sytax
Create view ViewName as select columns from tables
Types of views
1) Simple view
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90s to enhance the capabilities of SQL.
The PL/SQL Engine:
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in the
client system (client-side) or in the database (server-side).
A Simple PL/SQL Block:
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.
PL/SQL Block consists of three sections:
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which are
used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and
Records, which stores data temporarily. Cursors are also declared in this section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END.
This is a mandatory section and is the section where the program logic is written to perform any task. The
programmatic constructs like loops, conditional statement and SQL statements form the part of execution
section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates
gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates
abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested
within other PL/SQL blocks. Comments can be used to document code.
How a Sample PL/SQL Block Looks
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
Advantages of PL/SQL
Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each
block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and
reused.
Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single
block, thereby reducing network traffic.
Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL
program. Once an exception is caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.
DECLARE
var_salary number(6);
var_emp_id number(6) = 1116;
BEGIN
SELECT salary
INTO var_salary
FROM employee
WHERE emp_id = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee '
|| var_emp_id || ' has salary ' || var_salary);
END;
/
Scope of PS/SQL Variables
Local variables - These are declared in a inner block and cannot be referenced by outside Blocks.
Global variables - These are declared in a outer block and can be referenced by its itself and by
its inner blocks.
PL/SQL Constants
Constant is a value used in a PL/SQL Block that remains unchanged throughout the program.
constant_name CONSTANT datatype := VALUE;
DECLARE
salary_increase CONSTANT number(3);
BEGIN
salary_increase := 100;
dbms_output.put_line (salary_increase);
END;
Iterative Statements in PL/SQL
Iterative control Statements are used when we want to repeat the execution of one or more statements for
specified number of times.
Select statement
Begin
Open [cursor name];
Fetch [cursor name] into [return value];
Close [cursor name];
End;
Eg :-Declare cursor c1 is select * from emp;
V_emp emp%rowtype;
Begin
Open c1;
Loop
Fetch c1 into v_emp;
Dbms_output.put_line(The emp name is ||v_emp.ename);
End loop;
Close c1;
End;
TYPES OF CURSORS
There are two types of cursors
(1) An IMPLICIT cursor is automatically declared by Oracle every time an SQL statement is
executed. The user will not be aware of this happening and will not be able to control or process
the information in an implicit cursor.
DECLARE var_rows number (5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
END;
(2) An EXPLICIT cursor is defined by the program for any query that returns more than one row of
data. That means the programmer has declared the cursor within the PL/SQL code block. This
declaration allows for the application to sequentially process each row of data as it is returned by
the cursor.
DECLARE
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
IF NOT sales_cur%ISOPEN THEN
OPEN sales_cur;
END IF;
LOOP
FETCH emp_cur INTO emp_rec;
EXIT WHEN emp_cur%NOTFOUND;
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
/
Explicit Cursor Attributes
%NOTFOUND cursor_name%NOTFOUND A Boolean attribute that re-turns TRUE if the previous
FETCH did not return a row, and FALSE if it did.
%FOUND cursor_name%FOUND A Boolean attribute that re-turns TRUE if the previous FETCH
returned a row, and FALSE if it did not.
%ROWCOUNT cursor_name%ROWCOUNT # of records fetched from a cursor at that point in time.
%ISOPEN cursor_name%ISOPEN A Boolean attribute that re-turns TRUE if cursor is open, FALSE if it
is not.
Cursor with a FOR Loop:
When using FOR LOOP you need not declare a record or variables to store the cursor values, need not
open, fetch and close the cursor. These functions are accomplished by the FOR LOOP automatically.
DECLARE
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
/
Ref Cursor
A ref cursor is a data type that holds a cursor value in the same way that a varchar2
variable will hold a string value. A ref cursor can be opened on the server and
passed to the client as a unit rather than fetching one row at a time. One can use a
Loop
Vusername :=substr(i.f_name,2,3);
V_pwd:=substr(i.l_name,-2,2);
Update emp set username =vusername,pwd=vpwd ;
End loop;
Commit;
End;
Examples
--ANOTHER EG DISPLAYING VALUE OF A TABLE
DECLARE
CURSOR c1 IS SELECT * FROM emp;
e_rec emp%rowtype;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO e_rec;
DBMS_OUTPUT.PUT_LINE('Number: ' || ' ' || e_rec.empno);
DBMS_OUTPUT.PUT_LINE('Name : ' || ' ' || e_rec.ename);
DBMS_OUTPUT.PUT_LINE('Salary: ' || ' ' || e_rec.sal);
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;
Procudere
Procedure is a named block which are logically grouped sql and plsql statements
that performs specific tasks.
Syntax:-
1) Extensionality
2) Modularity
3) Maintainability
4) Reusability
5) One time compilation
PL/SQL Functions
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a
procedure and a function is, a function must always return a value, but a procedure may or may not return
a value.
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
CREATE OR REPLACE FUNCTION employer_details_func
RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl WHERE empID = '100';
RETURN emp_name;
END;
/
Function
A function always returns a value using return
statement.
Packages:
Oracle allows grouping stored procedures, functions, variables, constants, cursors
and exceptions into packages.
A package consist of
1) Package specification: - The package specification contains information about the package. The package specification
lists the available procedures and functions. The package specification generally doesn't contain the
code.
2) Package body: -- The package body contains the actual code.
Advantages
1) We can reduce input/output operations
2) Multiple interactions with database.
3) Improve performance while accessing sub programs from remote client.
4) Over loading
Syntax for package specification
Create or replace package <package name>
{is/as}
<package specification>
End <package name>;
Syntax for package Body
create or replace package body <package name>
{is/as}
<package body>
PL/SQL Collections
Collections are composite data types. Collections allow treating several variables as a unit. A collection
combines variables of the same type.
VARRAY: -- A VARRAY is data type similar to an array. A VARRAY has a fixed limit on its size,
Specified as part of declaration. Elements are inserted into VARRAY starting at index 1, up to maximum
length declared in the varray type. The maximum size of the VARRAY is 2 GB.
Syntax: -- TYPE <type name> is VARRAY (<Limit>) of <element type>;
Eg:-Declare
Type ABC is varray(10) of number;
V1 ABC :=abc(1,2,3,4,5,6)
Begin
Dbms_output.put_line(v1(1));
End;
By using select query
Declare
Type abc is varray (10) of number;
V2 abc;
Cusrsor c1 is select empno from emp where rownum<10;
V_emp abc;
Counter number :=1;
Begin
V2:=abc();
For I in 1 .. 10
Loop
V2.extend();
V2(i):=i;
Dbms_output.put_line(v2(i));
End loop;
V_emp :=abc();
For rec in c1
Loop
V_emp.extend();
V_emp(Counter) :=rec.empno;
Counter:=counter+1;
Dbms_output.put_line(v_emp(Counter));
End loop;
End;
1)
2)
3)
4)
5)
6)
7)
8)
COUNT :-- Returns the total number of elements that a collection currently contains.
LIMIT :-- Returns the Maximum number of elements for a Varray or NULL for Nested Tables.
EXISTS(N) :-- Returns TRUE if the Nth element in a collection exists; otherwise FALSE.
FIRST :-- Returns the First index numbers in a collection that uses integer subscripts.
LAST :-- Returns the Last index numbers in a collection that uses integer subscripts.
PRIOR :-- Returns the index number that precedes index N in a collection
NEXT :-- Returns the index number that succeeds index N.
EXTEND :-- Add a null element to a collection.
TRIM :-- Removes one element from the end of a collection
NESTED TABLES
A Nested table is thought of a database table which has no limit on its size. Elements are inserted into
nested table starting at index 1. The maximum size of the varray is 2 GB.
SYNTAX :-Type <type name> is table of <table type>;
Eg:-Declare
Type abc is table of number;
V2 abc;
1)
2)
3)
4)
5)
6)
7)
8)
COUNT :-- Returns the total number of elements that a collection currently contains.
LIMIT :-- Returns the Maximum number of elements for a Varray or NULL for Nested Tables.
EXISTS(N) :-- Returns TRUE if the Nth element in a collection exists; otherwise FALSE.
FIRST :-- Returns the First index numbers in a collection that uses integer subscripts.
LAST :-- Returns the Last index numbers in a collection that uses integer subscripts.
PRIOR :-- Returns the index number that precedes index N in a collection
NEXT :-- Returns the index number that succeeds index N.
EXTEND :-- Add a null element to a collection.
DELETE(N) :-- DELETE N element from the collection
BULK COLLECT:-Bulk Collect is used to retrieve all the records from the cursor into the array in one short. It will increase
the performance and it will reduce the context switches between sql engine and plsql engine.
The examples of bulk collect
Declare
Type t_eno is table of emp.empno%type;
Type t_ename is table of emp.ename%type;
V_eno t_eno;
V_ename t_ename;
Cursor c1 is select empno,ename from emp;
Begin
Open c1;
Fetch c1 bulk collect into v_eno,v_ename;
Close c1;
For I in v_eno.first .. v_eno.last
Loop
Dbms_output.put_line(empno is ||v_eno(i) || emp name is ||v_ename(i));
End loop;
End;
2nd example
Declare
Type abc is table of emp%rowtype index by pls_integer;
V abc;
X number;
Y emp%rowtype;
Begin
Select * from bulk collect into v from emp;
X:=1;
Loop
Dbms_output.put_line(v(x).ename);
X:=v.next(x);
Exit when x is null;
End loop;
End;
EXCEPTIONS HANDLING
PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception
Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) a message
k
Syntax:-DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;
Types of Exception.
There are 3 types of Exceptions.
Implicit exception
a) Named System Exceptions or predefined exception
b) Unnamed System Exceptions or non-predefined exception
Explicit Exception
c) User-defined Exceptions
Named System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are
some system exceptions which are raised frequently, so they are pre-defined and given a name in Oracle
which are known as Named System Exceptions.
BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;
Pre-defined exceptions are
Exception
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
INVALID_CURSOR
INVALID_NUMBER
LOGIN_DENIED
Exception
NO_DATA_FOUND
NOT_LOGGED_ON
PROGRAM_ERROR
ROWTYPE_MISMATCH
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
TOO_MANY_ROWS
Exception
VALUE_ERROR
ZERO_DIVIDE
---- || err_msg);
User-defined Exceptions
User defined exceptions are explicitly define exceptions based on business rules.
RAISE_APPLICATION_ERROR
Raise Application error is a procedure of package DBMS_STANDARD which allows to issue an user
defined error message from stored sub program or database trigger.
Eg:-Declare
V_empno emp.empno%type :=&empno;
V_sal number;
E_high_sal exception;
Begin
Select sal into v_sal from emp where empno=v_empno;
If v_sal>2000 then
Raise e_high_Sal;
End if;
Update emp set sal=sal*0.01 where empno=v_empno;
Exception
When e_high_sal then
Raise_application_error(-20001,Salary is to high);
End;
/
You could use the SQLERRM function to raise an error as follows:
Exception
When other then
Raise_application_error(-20001,an error was encountered ||SQLCODE||-ERROR-||SQLERRM);
END;
/
Or you could log the error to a table using the SQLERRM function as follows:
Exception
When others then
Err_code :=sqlcode;
Err_msg := SUBSTR(SQLERRM, 1, 200);
Insert into audit_table (error_number,error_message) values(err_code,err_msg);
End;
/
Triggers
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is
executed on a database table. A trigger is triggered automatically when an associated DML statement is
executed.
Syntax for Creating a Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
Advantages of Triggers
1) Audit data modifications.
2) Log events transparency
3) Ensure complex business rules derived columns values automatically
4) Implements complex security authorization
5) Maintains replicate tables
cp old_filename new_filename
mv - move a file
Rename a file with the move command, mv.
mv old_filename new_filename
rm - remove a file
Remove a file with the rm, remove, command.
chmod - change file permissions
read=4, write=2, execute=1 or read=r, write=w, execute=x
+ add permissions
- remove permissions
= set permissions
chown - change ownership
chown new_owner file
chgrp - change group
chgrp new_group file
echo - echo a statement (print the value)
echo Hello Class or echo "Hello Class"
cat - concatenate a file
Display the contents of a file with the concatenate command, cat.
head - display the start of a file
head displays the head, or start, of the file
tail - display the end of a file
df - summarize disk block and file usage
du - report disk space in use
ps is used to report on processes currently running on the system.
kill - terminate a process
who - list current users
who reports who is logged in at the present time.
Syntax
who [am i]
whereis - report program locations
whereis reports the filenames of source, binary, and manual page files associated with command(s).
hostname/uname - name of machine
script - record your screen I/O
date - current date and time
Syntax
date [options] [+format]
Common Options
-u use Universal Time (or Greenwich Mean Time)
+format specify the output format
%a weekday abbreviation, Sun to Sat
%h month abbreviation, Jan to Dec
%j day of year, 001 to 366
%n <new-line>
%t <TAB>
%y last 2 digits of year, 00 to 99
%D MM/DD/YY date
%H hour, 00 to 23
%M minute, 00 to 59
%S second, 00 to 59
%T HH:MM:SS time
Examples
beauty condron>date
Mon Jun 10 09:01:05 EDT 1996
beauty condron>date -u
Mon Jun 10 13:01:33 GMT 1996
beauty condron>date +%a%t%D
Mon 06/10/96
beauty condron>date '+%y:%j'
96:162
DUAL
This is a single row and single column dummy table provided by oracle. This is used to perform
mathematical calculations without using a table.
Group By
The Oracle GROUP BY Clause is used in a select statement to collect data across multiple records and
group the results by one or more columns.
Having By
The Oracle HAVING Clause is used in combination with the group by clause to restrict the groups of
returned rows to only those whose the condition is TRUE.
Where Clause
The Oracle WHERE clause is used to filter the results from a select,insert,update and delete statement.
From Clause
The Oracle/PLSQL FROM clause is used to list the tables and any join information required for the
Oracle query.
Distinct Clause
The Oracle DISTINCT clause is used to remove duplicates from the result set. The DISTINCT clause can
only be used with select statements.
Order By
The Oracle ORDER BY clause is used to sort the records in your result set. The ORDER BY clause can
only be used in select statements.
Mutating Error
Mutating error normally occurs when we are performing some DML operations and we are
trying to select the affected record from the same trigger. So basically we are trying to select
records in the trigger from the table that owns the trigger. This creates inconsistency and Oracle
throws a mutating error.
How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where a certain table, field or
expression is referenced in your PL/SQL source code.
SELECTTYPE,NAME,LINE
FROMUSER_SOURCE
WHEREUPPER(TEXT)LIKE'%&KEYWORD%';
CREATETABLESOURCE_HISTCreatehistory
table
ASSELECTSYSDATECHANGE_DATE,USER_SOURCE.*
FROMUSER_SOURCEWHERE1=2;
CREATEORREPLACETRIGGERchange_histStorecodein
histtable
AFTERCREATEONSCOTT.SCHEMAChangeSCOTT
toyourschemaname
DECLARE
BEGIN
ifDICTIONARY_OBJ_TYPEin('PROCEDURE','FUNCTION',
'PACKAGE','PACKAGEBODY','TYPE')then
StoreoldcodeinSOURCE_HISTtable
INSERTINTOSOURCE_HIST
SELECTsysdate,user_source.*FROMUSER_SOURCE
WHERETYPE=DICTIONARY_OBJ_TYPE
ANDNAME=DICTIONARY_OBJ_NAME;
endif;
EXCEPTION
WHENOTHERSTHEN
raise_application_error(20000,SQLERRM);
END;
/
showerrors
BEGIN
fileHandler:=UTL_FILE.FOPEN('/tmp','myfile','w');
UTL_FILE.PUTF(fileHandler,'Lookma,I''mwritingto
afile!!!\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHENutl_file.invalid_pathTHEN
raise_application_error(20000,'ERROR:Invalid
pathforfileorpathnotinINIT.ORA.');
END;
/
NOTE: The DDL statement in quotes should not be terminated with a semicolon.
Starting from Oracle8i one can use the EXECUTE IMMEDIATE statement to execute
dynamic SQL and PL/SQL statements (statements created at run-time). Look at these examples.
Note that statements are NOT terminated by semicolons:
EXECUTEIMMEDIATE'CREATETABLEx(aNUMBER)';
Usingbindvariables...
sql_stmt:='INSERTINTOdeptVALUES(:1,:2,:3)';
EXECUTEIMMEDIATEsql_stmtUSINGdept_id,dept_name,
location;
Returningacursor...
sql_stmt:='SELECT*FROMempWHEREempno=:id';
EXECUTEIMMEDIATEsql_stmtINTOemp_recUSINGemp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic
statements. Look at these examples:
CREATEORREPLACEPROCEDUREDYNSQLAS
curinteger;
rcinteger;
BEGIN
cur:=DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATETABLEX(YDATE)',
DBMS_SQL.NATIVE);
rc:=DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
',DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor,':x',no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor,1,v_dname,
20);
v_rows:=DBMS_SQL.EXECUTE(v_cursor);
loop
ifDBMS_SQL.FETCH_ROWS(v_cursor)=0then
exit;
endif;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor,1,v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartmentname:'||
v_dname);
endloop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
whenothersthen
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(20000,'Unknown
ExceptionRaised:'||sqlcode||''||sqlerrm);
END;
/
However, one can use embedded SQL statements to obtain sequence values:
selectsq_sequence.NEXTVALinto:ifromdual;
ENDLOOP;
END;
/