www.accelfrontline.in
ACCEL FRONTLINE LTDACCEL FRONTLINE LTD
Wishes & Welcomes all its participants
www.accelfrontline.in
Features of DBMS
• Simplicity• Query Language is non-procedural• Physical impln storage depends on
OS• Recovery depends on OS
www.accelfrontline.in
Features Of Good DBMS • The facility of retrieving and manipulating
data irrespective of no of tables used.• The language should be easy• Should be powerful enough to have minimal
code and so less maintenance• Resources like memory and secondary
storages should be handled by DBMS• It should have Multi-user support
www.accelfrontline.in
Concept of Relation
• Relation is nothing but Set• A Database is said to be relational if data
is stored in the form of relation
www.accelfrontline.in
Advantages of RDBMS
• Information representation is simple in table form
• Non-Procedural language is easily operated
• Set Operations are used for data operations
• Data from multiple tables is retrieved in simple way by forming Cartesian product
www.accelfrontline.in
Features Of Oracle
• All operations are done using non-procedural language
• Multi-user Environment• Security• Concurrent Operations• Query Optimization• Transparent Indexing, Backup and Recovery
www.accelfrontline.in
Components Of Oracle• SQL PLUS• PL/SQL• SQL FORMS• SQL REPORT WRITER
www.accelfrontline.in
Introduction to SQL
• The language used to access data within Oracle databases
• Non-Procedural Language.• Unified Language• Common Language for all relational
databases
www.accelfrontline.in
Sql is made of three sub-languages such as Data Definition Language. Data Manipulation Language. Data Control Language.
www.accelfrontline.in
DEFINITIONS• Data Definition Language ( DDL) Consists of commands to create the objects, such as tables, views, Indexes etc. Syntax : CREATE TABLE <table-name>(<column1 –name> datatype,<column2_name> datatype,
.
.
. <column-name> dataype);
www.accelfrontline.in
Data Definition Language• Example :CREATE TABLE General_Account_Master_Table ( acct_name varchar2(30) acid varchar2(11), foracid varchar2(16), clr_bal_amt number(17,2), schm_code varchar2(5)
acct_opn_date date ) ;
www.accelfrontline.in
Definitions• Data Manipulation Language ( DML ) Used for query, insertion ,deletion and updating of
information stored in the database. Syntax : INSERT INTO <table-name> VALUES ( ‘value1’,’value2’,’value3’,value4,’value5’,’value6’) ;
www.accelfrontline.in
Data Manipulation Language• Example: INSERTINSERT INTO General_Account_Master_Table
VALUES (‘RAJKUMAR’,‘DL123’,’SB123’, 10000,’SBGEN’,’12-02-2002’);
INSERT INTO General_Account_Master_Table VALUES(‘HINDUSTAN’,‘DL124’,’SB124’,
11000,’CDGEN’,’12-02-2002’ );
www.accelfrontline.in
Data Manipulation Language• Example: UPDATE
Update General_Account_Master_Table set clr_bal_amt = 20000 where ltrim(foracid)=’SB123’;
www.accelfrontline.in
Data Manipulation Language• Example : DELETE • Syntax:DELETE <table-name>WHERE <conditions>Example :• DELETE general_account_master_table
WHERE acid =’DL123’
www.accelfrontline.in
DATA CONTROL LANGUAGE • COMMIT
Will commit the changes that has been made to the table.
Considering the above eg for UPDATE ,when the statement is committed the clr_bal_amt for that foracid will be Rs 20000.
• ROLLBACK
Will rollback all the changes that has been made to the table,ie in the above case the value of clr_bal_Amt will be Rs 10000
www.accelfrontline.in
Querying Database Tables The select statement instructs the database to retrieve information from a table
• Syntax: SELECT < column-list > FROM <table-name>
WHERE <condition> • Example: SELECT foracid from
General_Account_Master_Table WHERE acid =’DL123’;
www.accelfrontline.in
Conditional Retrieval of Rows
• The WHERE clause is used along with the SELECT statement to specify the condition, based on which the rows will be extracted from a table with SELECT.
• Operators used to specify the conditions:
www.accelfrontline.in
Relational operators: • = : Equal to • > : Greater than• < : Less than• >= : Greater than or equal to• <= : Less than or equal to • <>, != : Not equal to
www.accelfrontline.in
Examples: SELECT foracid , acid FROM
General_Account_Master_Table WHERE clr_bal_amt = 10000;
SELECT foracid , acid FROM
General_Account_Master_TableWHERE clr_bal_amt <= 10000;
www.accelfrontline.in
Logical operators
• AND : Logical AND
• OR : Logical OR • NOT : Logical NOT
www.accelfrontline.in
Examples- Logical Operators• SELECT foracid FROM
General_Account_Master_TableWHERE acid =’DL123’ OR acid = ‘DL124’ ; • SELECT foracid FROM
General_Account_Master_TableWHERE acid =’DL123’ AND clr_bal_amt >= 10000 ;
www.accelfrontline.in
Special Operators• IN : Checking a value in a set
• BETWEEN : checking a value within a range
• LIKE : Matching a patter from a column
www.accelfrontline.in
Examples – Special OperatorsSELECT foracid , cust_id , acct_name from General_Account_Master_Table WHERE Schm_code IN (‘SBGEN’,’CDGEN’ );
SELECT acct_opn_date , acid FROM General_Account_Master_Table WHERE acct_name LIKE ‘RAJ%’;
www.accelfrontline.in
Special operators…..,Union Operator
Eliminates duplicate rowsExample :
Select acid, tran_amt, tran_date, tran_particulars, tran_id from dtd Where acid = (select acid from gam where foracid = ‘&acid’)
Union Select acid, tran_amt, tran_date, tran_particular, tran_id from ctd where acid = (Select acid from gam where foracid = ‘&acid’);
www.accelfrontline.in
Special Operator..,Union All It does not eliminates duplicate rows .Example :Select acid, Tran_amt, Tran_date, Tran_particular, Tran_id from dtd
where acid = (select acid from gam where foracid = ‘&acid’) UNION ALL
select acid, Tran_amt ,Tran_date, Tran_particular, Tran_id from ctd where acid = (select acid from gam where foracid = ‘&acid’);
www.accelfrontline.in
Special Operator…,Intersect Operator
This returns only those rows returned by bothQueries
Example : Select fxd_crncy_code,var_crncy_code from rtl intersect
select fxd_crncy_code,var_crncy_code from rth;
www.accelfrontline.in
Special Operator…,Minus OperatorThis returns only those rows returned by the first
query but not in the second.Example :Select cust_id from cmg minus select cust_id from
gam;
www.accelfrontline.in
SQL Plus functions• Dual Table :It is created along with the data dictionary .It is schema of the user sys but accessible to all the users.Useful for computing a constant expression with the select statement .Dual has only one row ,the constant is only returned once.Example :Select sysdate from dual;
www.accelfrontline.in
Pseudo Columns• It is a column that yields a value when selected
but which is not an actual column of a table . Example SYSDATE.
Some Oracle pseudo columns:Null : This is used to assign in place of missing
values.Rownum : Returns the sequence number in which
a row was returned when selected from a table.Sysdate: Returns current date and time
www.accelfrontline.in
Number functions..,1)ABS: It returns the absolute value of N Select abs (-15) “ ABSOLUTE “ from dual; Result : 152) CEIL:
It returns smallest integer greater that or equal to N Select ceil (15.1) “ CEILING “ from dual; Result : 16 3) FLOOR:
Returns largest integer equal to or less than N Select floor (15.9) “ FLOOR “ from dual;Result is 15
www.accelfrontline.in
Numeric Functions..,4) MOD:• Returns remainder of m divided by n • Select mod (12,3) from dual;• Result is 05) ROUND:• Round (n [, m]) • Returns n rounded to m places right of the decimal point m can be negative to round off digits left
to the decimal point .m must be an integer Select round (55.1234,1) from dual;
• Result is 55.1
• Select round (56.1234, -2) from dual;• Result: 100 • Select round (45.12434, -2) from dual• Result: 0
www.accelfrontline.in
Numeric Functions..,6) INITCAP: Select initcap (‘ram’) from dual; Result: Ram 7) Lower:
Select LOWER (‘ M/S HINDUSTAN LEVER LTD ‘) from dual;
Result: m/s Hindustan lever ltd2) 8) LPAD: Left padded to length n with the sequence of characters. Select lpad (‘PAGE 1’, 15,’*’) from dual;
Result: *********PAGE 1
www.accelfrontline.in
Numeric Functions..,9) RPAD:Right paded to length n with characters
Select rpad (‘PAGE 1’, 15,’*’) from dual;
– Result: PAGE 1*********
• 10) LTRIM: Select ltrim (‘1234ALPHA’,’12’) from dual;
Result: 34ALPHA
• 11) RTRIM: Select rtrim (‘BROWINGXYXY’,’XY’) from dual;
Result: BROWING
www.accelfrontline.in
Numeric functions..,• 12) SUBSTR
Select substr (‘ABCDEFG’, 3,4) from dual;Result: CDEF
Select substr (‘ABCDEFG’, -5) from dual; Result: CDEFG
• 13) UPPER Select upper (‘Large’) from dual; Result: LARGE
www.accelfrontline.in
AGGREGATE FUNCTIONSAggregate functions are used to produce summary data using
tables AVG(column-name) –Returns the average of the values in
the column SUM(column-name) – Returns the sum of values specified in
the column MIN(column-name) – Returns the minimum of value specified
in the column MAX(column-name) - Returns the minimum of value specified
in the column COUNT(*) - Returns the total no of records specified in the
table
www.accelfrontline.in
Examples-Aggregate Functions
SELECT count(*),schm_code FROM general_account_master_table
GROUP BY schm_code; SELECT Avg(clr_bal_amt) FROM
general_account_master_tableWHERE schm_code =’SBGEN’;
www.accelfrontline.in
Examples – Aggregate Functions SELECT Max(clr_bal_amt),schm_code FROM general_account_master_table GROUP BY schm_code ORDER BY schm_code ; SELECT SUM(clr_bal_amt) FROM
general_account_master_table WHERE schm_code =’SBGEN’;
www.accelfrontline.in
JOINS• SQL server provides a method of retrieving data from
more than one table using joins .A join can be defined as an operation that includes retrieval of
data from more than one table at a time . • The various types of joins are Equii join Self join Outer join
www.accelfrontline.in
Example : Equi Join• Equi Join :• It selects data from both the tables having a
common column.• It selects data based on the equality joining
condition.
Example :• Select gam.foracid,cmg.cust_id ,cmg.cust_name
from cmg,gam where • Gam.cust_id = cmg.cust_id
www.accelfrontline.in
• Self join:In a self-join, rows from a table are correlated to rows in the same table. Since the same table is used twice for comparison, an alias name is given which differentiates the two copies of the table.
Select c1.cust_id,c1.cust_name,c1.introd_cust_id,c2.cust_name From cmg c1,cmg c2 where C1.introd_cust_id = c2.cust_id
www.accelfrontline.in
• Outer join:• An outer join displays data from one table and
only matching join data from the second table .In the rows selected for non-matching data NULL will be displayed in the non-matching columns of the second table.
• Select cmg.cust_name,gam.foracid from gam ,cmg where • Cmg.cust_id = gam.cust_id(+)
www.accelfrontline.in
NESTED QUERIES
SQL has an ability to nest queries within one another . A sub query is a SELECT statement that is nested within another SELECT statement and which returns intermediate results .SQL first evaluates the inner query (or sub query) within the WHERE clause. The inner query generates values that are tested in the product of the outer query, determining when it will be true. The return value of inner query is then substituted in the condition of the outer query.
www.accelfrontline.in
Advantages Sub queries allows a developer to build
powerful commands out of simple ones.
The nested sub query is very useful when you need to select rows from a table with a condition that depends on the data in the table itself.
www.accelfrontline.in
Example • SELECT gsp.schm_type , gam.acct_name , sanct_lim sanctioned_limit,
• (adhoc_lim+clean_adhoc_lim+emer_advn+clean_emer_advn+• single_tran_lim+clean_single_tran_lim) total_tod_allowed,•
(sanct_lim+adhoc_lim+clean_adhoc_lim+emer_advn+clean_emer_advn+single_tran_lim+clean_single_tran_lim) aggregate_limit,
• drwng_power advance_value, (clr_bal_amt+un_clr_bal_amt) balance• FROM gam,gsp• WHERE acct_ownership != 'O' and• gam.del_flg != 'Y' and• gam.schm_code = gsp.schm_code and• ((gsp.schm_type = 'CCA' and• (gam.acct_rpt_code = '020100' OR • gam.acct_rpt_code = 2000')) OR• (gsp.schm_type = 'CAA' and• (gam.acct_rpt_code = '425100' or gam.acct_rpt_code = '425200' or• gam.acct_rpt_code = '425300') and (clr_bal_amt+un_clr_bal_amt) < 0))• ORDER BY schm_type;
www.accelfrontline.in
USING AGGREGATE FUNCTIONS IN SUB QUERIES
SELECT foracid , clr_bal_amt , acid , schm_code FROM gam
WHERE Clr_bal_amt > (SELECT Avg (clr_bal_amt) FROM gam WHERE Schm_code IN (‘SBGEN’,’CDGEN’’));
www.accelfrontline.in
CORRELATED SUB QUERIES
• A correlated sub query can be defined as a query that depends on the outer query for its evaluation .In a correlated sub query, the WHERE clause references a table in the FROM clause of the outer query .In the case of correlated sub queries, the inner query is evaluated for each row of the table specified in the outer query
www.accelfrontline.in
Examples• SELECT count(distinct
lht.acid),Sum(lht.sanct_lim),sum(tran_date_bal) • FROM lht, eab , gam , gac , ach• WHERE lht.acid=eab.acid and • lht.acid = gam.acid • and gam.acid=gac.acid • and gam.acid=ach.b2k_id • and schm_type='laa' • and sector_code='prior'
Contd . . .
www.accelfrontline.in
Example – Contd…• and sub_sector_code='agrcr' • and main_classification_user='1'• and sub_classification_user='01'• and type_of_advn='terml' • and applicable_date=(select max(applicable_date) from
lht • WHERE l.acid=lht.acid • and applicable_date<='&1') • and eod_date<='&1' • and end_eod_date>='&1';
www.accelfrontline.in
PL/SQL • Support for SQL• Block Structure• Higher Productivity• Better Performance• Integration • Control structures• Modularity & Portability
www.accelfrontline.in
Introduction to PL/SQL BlockA PL/SQL block can be divided into three parts, namely, a declarative part an executable part and an exception handling part .the order is as shown:
• DECLARE
} declarationBEGIN
• } executable statements EXCEPTION} handlers
• END;
www.accelfrontline.in
• Objects can be declared in the declarative part, which can be used in the executable part for further manipulations .
• All the procedural statements are included in between the BEGIN and END statements.
• Errors that occur during execution are dealt in the exception handling
www.accelfrontline.in
Pl/SQL character set Pl/SQL character set includes the following:
Upper and lowercase letters. They are not case sensitive except within strings and character literals.
Numerals from 0 to 9 All special symbols and characters
www.accelfrontline.in
• Pl/SQl text contains groups of characters known as lexical units. The following are the lexical units:
• Identifiers• Literals• Comments • Delimiters (simple and compound symbols)
www.accelfrontline.in
DATATYPES AND THEIR USAGE • Pl/SQL Data Types Character• Raw• Long Raw• Row id• String• Varchar• Varchar2• Date • Boolean
www.accelfrontline.in
Data types• Binary Integer : Natural• Decimal : Number• Double Precision : Positive• Float : Real• Int : Smallint• Integer : Char
www.accelfrontline.in
Attributes ….Attributes allow to refer to data types and object from the database .PL/SQL variables and constants can have attributes supported by PL/SQL
%type%rowtype
www.accelfrontline.in
Definitions%type
• It is used when declaring variables that refer to the database columns .
www.accelfrontline.in
%type…. ExampleDeclareAcctid gam.acid %type
Where acctid is the variable name , gam is the table name and acid is the name of the column
www.accelfrontline.in
Definitions … %rowtype%ROWTYPE
%rowtype attribute provides a record type that represents a row in a table.
The record store an entire row of data selected from the table or fetched by a cursor.
www.accelfrontline.in
%rowtype …. ExamplesDeclare
Cust_name cmg %rowtype
In the above example cust_name represents the entire row in the table and cmg is the name of the table.
www.accelfrontline.in
Logical comparisons Pl/SQL supports the comparison of variables and constants in SQL and PL/SQL statements.These comparisons called Boolean expressions , are often connected by logical operators AND, OR and NOT .The following are the three kinds of Boolean expressions.
• Numeric • Character • Date
www.accelfrontline.in
Numeric Boolean Expression • Operator Meaning Example
= is equal to acctid = 1234!= is not Equal to acctid != 1234
< is lesser than acctid < 1234<= is lesser than acctid <= 1234 or equal to
> is greater than acctid > 1234 >= is greater than acctid >= 1234
or equal to
www.accelfrontline.in
Date Boolean Expressions Example:
SELECT acct_name , foracid , cust_id FROM gam WHERE acct_opn_date =’&ddate’;
www.accelfrontline.in
Control structures
Conditional control
Iterative control
Sequential control
www.accelfrontline.in
Conditional control
• Sequence of statements can be executed based if some conditions using the IF statements.
• There are three forms of IF statements, namely IF THEN, IF THEN ELSE and IF THEN ELSE IF
www.accelfrontline.in
Syntax – Conditional Structures
IF condition then Sequence of statementsENDIF
The sequence of statements is executed only if the condition evaluates to True. If it is false or Null, then the control passes to the statement after end If.An else clause in the If Then statement defines what is to be done if the condition evaluates to False or Null. An IF THEN ELSE IF stat can be used to select one of several mutually exclusive alternatives.
www.accelfrontline.in
Iterative Control
Simple Loop
For Loop
While Loop
www.accelfrontline.in
SIMPLE LOOP The keyword loop should be placed before the first statement in the sequences and the keyword end loop after the last statement in the sequence
SYNTAX:loop
-- sequence of statements End Loop
www.accelfrontline.in
Simple Loop …. ExampleExample :
Declare a number := 100; BEGIN
Loop a:= a + 25;Dbms_output.put_line(to char(a));EXIT when a = 250;End loop
End;
The EXIT WHEN statements allow completing a loop if further processing is undesirable.
www.accelfrontline.in
WHILE LOOP
• The while loop statement includes a condition associated with a sequence of statement. If the condition evaluates to TRUE, the sequence of statements will be executed an again control resumes at the top of the loop. If the condition evaluates to false, the loop is by passed and the control passes to the next statement.
www.accelfrontline.in
While LoopSYNTAX
WHILE < condition >Loop
Sequence of statements End loop
www.accelfrontline.in
While Loop … ExampleWHILE numdmds <= no_of_flows
loopdmd_date := add_months(dmd_date, frequency);
numdmds := numdmds + 1;dbms_output.put_line(numdmds);
end loop;
www.accelfrontline.in
FOR LOOPfor i in 1..33 loop
dbms_output.put_line(‘THIS IS LINE NUMBER’ ||’ ’||i );end loop;end;
www.accelfrontline.in
For Loop … ExampleIn the above example, ‘i’ is initialized to 1 in the beginning and is incremented upto ‘33’. Once the number ‘33’ is reached, the loop will break. The output of the above loop will look like
• This is line number 1• This is line number 2• This is line ……………..• This is line number 33
www.accelfrontline.in
Cursor ManagementA work area called private SQL area is used by the ORACLE server to execute Sql stats and to store processed information. Pl/SQL uses cursors to name the private SQL area and to access the stored information. There are two types of cursors. They are
• Explicit cursor• Implicit cursor
www.accelfrontline.in
Cursor Management• A cursor can be declared in the declarative
part of a Pl/SQL block,a subprogram or a package .The syntax for declaring a cursor is as follows.
• CURSOR < cursor_name> is <select
statement>
www.accelfrontline.in
EXPLICIT CURSOR• The set of rows returned by a query can contain zero
or multiple rows depending upon the query defined.• These rows are called the active set. The cursor
will point to the current row in the active set.After declaring a cursor, we can use the foll commands to control the cursor
• Open • Fetch • Close
www.accelfrontline.in
• The open statement executes the query, identifies the active set and positions the cursor before the first row .the syntax is as follows
• OPEN < cursor_name>;
www.accelfrontline.in
Cursors…..,• The fetch statement retrieves the current row
and advances the cursor to the next row to fetch the remaining rows.
• Syntax for fetch is as follows FETCH <cursor_name> Into < column_name>;
www.accelfrontline.in
Cursors …..,• After processing the last row in the active
set, the cursor is disabled with the help of the close command .
• The syntax is as follows
• CLOSE < cusrsor_name>;
www.accelfrontline.in
Cursor … ExampleDECLARE CURSOR c2 is
SELECT acct_name , foracid , schm_code From gam WHERE cust_id =’&id’;Name gam.acct_name%type;Acctnumber gam.foracid%type;Schmcode gam.schm_code%type;
BEGINOPEN C2;Loop FETCH c2 INTO name, acctnumber;schmcode;
If c2%rowcount > 2 thenDbms_output.put_line(‘fetches more than tworows’);End ifExit when c2%rowcount < 2;
End loop; CLOSE C2;End;
www.accelfrontline.in
Attributes• %NOTFOUND • After opening a cursor a fetch stat is used to fetch
rows from the active set, one at a time .• The attribute %notfound indicates wether fetch
statement returns row from the active set .• If the last fetch fails to return a row, then %notfound
evaluates to true, else it evaluates to false
www.accelfrontline.in
Attributes• %FOUND
It is the logical opposite of %not found .It evaluates to true if the last fetch statement succeeds .It would be evaluated to false if the last fetch command failed because no more rows were available.
• %ROWCOUNT The %rowcount attribute is used to return the number of
rows fetched before the first fetch %rowcount is zero. When the fetch statement returns a row, the number is incremented.
www.accelfrontline.in
Examples• DECLARE
CURSOR c2 is SELECT acct_name,foracid ,schm_code From gam WHERE cust_id =’&id’;
• Name gam.acct_name%type;• Acctnumber gam.foracid%type;• Schmcode gam.schm_code%type;
Begin
OPEN C2;Loop
• FETCH c2 INTO name, acctnumber;schmcode;If c2%rowcount > 2 then
Dbms_output.put_line(‘fetches more than two rows’);End if
• Exit when c2%rowcount < 2;
End loop;• CLOSE C2;• End;
www.accelfrontline.in
IMPLICIT CURSOR• PL/SQL implicitly declares cursors for all SQL
data manipulation statements, including queries that return one row .
• For queries that return more than one row, we should use explicit cursors to access the rows individually.
• Implicit cursor attributes can be used to access
information about the most recently executed SQL statement .
www.accelfrontline.in
Implicit Cursor…,• The most recently executed statement is
referred as ‘SQLCURSOR’. The implicit cursor attributes are
• %notfound• %found• %rowcount• %isopen
www.accelfrontline.in
ExamplesDeclare CURSOR C1 is Select cust_name from gam
WHERE ltrim(cust_id) = 'JKB155';
Cmg_rec c1%rowtype ;Begin
For cmg_rec in c1Loop
UPDATE cmg set cust_name ='Paul' WHERE ltrim(cust_id) ='JKB155';
commit;If sql%rowcount > 1 thenDbms_output.put_line ( ' More Than one Record Exists ');End if;End loop;End;
/
www.accelfrontline.in
CONCEPT OF ERROR HANDLING Error condition in PL/SQL is termed as an exception. There are two types of exception. They are
Predefined exception User-Defined exception
www.accelfrontline.in
PREDEFINED EXCEPTION • An exception is raised implicitly when a
PL/SQL program violates Oracle rule. • The following are predefined exceptions
supported by PL/SQL
www.accelfrontline.in
Predefined Exceptions ..,• No_Data_Found
This exception is raised when select statement returns no rows.
• Cursor_already_open This exception is raised when we try to open a
cursor, which is already opened. • Dup_val_on_index
This exception is raised when we insert duplicate values in a column, which is defined as unique index.
www.accelfrontline.in
Predefined Exceptions..,• Storage_Error
This exception is raised if PL/SQL runs out of memory or if the memory is corrupted.Program_Error
This exception is raised if the PL/SQL has an internal problem.
• Zero DivideThis exception is raised when we try to divide a
number by zero.
www.accelfrontline.in
Predefined Exceptions..,• Invalid _cursor
This exception is raised when we violate cursor operation. For example when we try to close a cursor, which is not opened.
• Login_deniedThis exception is raised when we try to enter Oracle
using invalid username/password.• Too_many_rows
Raised when the select into statement returns more than one row.
www.accelfrontline.in
Predefined Exceptions..,• Syntax:
Begin<Sequence of statements>;Exception
• When < exception_name> thenSequence_of_statements;
• When others then /* the last exception in the exception handler */Sequence of statements;
• End;
www.accelfrontline.in
Examples ..,• • Declare
Custname cmg.cust_name%type• Begin
SELECT cust_name into custname from cmg WHERE cust_id =’JKB123’
Exception When no_data_found then Dbms_output.put_line (‘Item not found’);
• End;
www.accelfrontline.in
USER-DEFINED EXCEPTION
• A user defined exception should be declared and raised explicitly by a raise statement. It can be declared only in the declarative part of the PL/SQL block.
www.accelfrontline.in
User Defined Exception• Syntax
<exception_name> exception; Syntax for a raise statement follows.
Raise <exception_name>
www.accelfrontline.in
Examples..,• Declare
Zero_balance exception ;Clear_balance_amt (10,2);BeginSELECT clr_bal_amt into clear_balance_amt from gam WHERE foracid =’JKB345’If clear_balace_amt = 0 then Raise zero_balance;End if;Exception WHEN zero_balance then Dbms_output.put_line (‘Raised zero_balance exception’);End;
www.accelfrontline.in
SUBPROGRAMS• These are named PL/SQL blocks that can
accept parameters and can be invoked whenever required.
• Similar to a PL/SQL block, a subprogram can also have a declarative part, an executable part and an exception handling part.
www.accelfrontline.in
Advantages• Modularity – subprograms allow us to
break a program into manageable, well-defined logical modules.
• Reusability – subprograms once executed can be used in any number of applications.
• Maintainability – subprograms can simplify maintenance, because if a subprogram is affected, only its definition changes.
www.accelfrontline.in
SUBPROGRAMS• PL/SQL supports two types of
subprograms. They are
• Procedures • Functions
www.accelfrontline.in
PROCEDURES• A PROCEDURE is a sub program that
performs a specific action.
• A procedure can be called from any PL/SQL program.
• Procedures can also be invoked from the SQL prompt.
www.accelfrontline.in
PROCEDURES • Create or replace procedure < Proc –name >
[parameter list] is < Local declarations >;
• Begin(Executable statements)[Exception] (Exception handlers)
End;
www.accelfrontline.in
ExamplesCreate or replace procedure acctmaster (acctno) is
Custid varchar2 (7);Acctnumber varchar2 (16);Balance number (10,2);Begin BeginSELECT cust_id, foracid, clr_bal_amt into custid, acctnumber, balance from gam Where foracid = acctno;Exception When No_Data_Found thenAcctnumber: =’Account does not exist’;End;Dbms_output.put_line (custid, acctnumber, balance);End;
www.accelfrontline.in
FUNCTION• A FUNCTION is a sub program that
returns a value.
• A Function must have a RETURN clause.
www.accelfrontline.in
Actual Versus Formal Parameters• The variables or expressions referenced
in the parameter list of a sub program call are actual parameters.
• The variables declared in a sub program specification and referenced in the sub program body are formal parameters
www.accelfrontline.in
Argument Modes• Argument modes are used to define the
behaviour of formal parameters.• There are three arguments modes to be used
with any subprograms.
• IN- The IN parameter lets the user pass values to the called sub program. Inside the sub program, the IN parameter acts like a constant, therefore it cannot be modified.
www.accelfrontline.in
Argument Modes• OUT The OUT mode parameter lets the
user return values to the calling block. Inside the subprogram, the OUT parameter acts like an uninitialised variable. Therefore its value cannot be assigned to another variable or itself.
• IN OUT The IN OUT parameter lets the user pass initial values to the called sub program and returns updated values to the calling block
www.accelfrontline.in
Functions• Create or replace function < function-name>
[argument]Return data type is
(Local declaration)Begin
(Executable statements)[Exception]
(Exception handlers)End;
www.accelfrontline.in
Function - Examples• CREATE or replace function Sel_Eab(inputdt date, acctid varchar)• return number is• bal number;• Begin• Select• nvl(decode(gam.acct_crncy_code,'INR', tran_date_bal, var_crncy_unit (inputdt,
gct.report_rate_code, gam.acct_crncy_code, 'INR') * tran_date_bal),0)• into bal• from eab, gam, gct• Where eab.acid = acctid• and gam.acid=eab.acid• and eab.eod_date <= inputdt• and eab.end_eod_date >= inputdt ;• Return (bal);• End;
www.accelfrontline.in
STORED PACKAGES• A package is a database object that
groups logically related PL/SQL objects.
• Packages encapsulate related procedures, functions, associated cursors and variables together as a logical unit in the database.
www.accelfrontline.in
Stored Packages• Packages are made of two components: a) The
specifications and b) the body.
• The specification is the interface to applications and has declarative statements.
• The body of a package contains different procedures and functions
www.accelfrontline.in
Advantages• Packages offer several advantages, which includes:• MODULARITY
• EASIER APPLICATION DESIGN.
• INFORMATION HIDING.
• ADDED FUNCTIONALITY.
• BETTER PERFORMANCE.
www.accelfrontline.in
Packages
www.accelfrontline.in
PACKAGESOracle Supplied Packages
Calendar, DBMS_ALERTS, DBMS_APP Oracle Supplied PackagesCalendar, DBMS_ALERTS, DBMS_APPLICATION_INFO, DBMS_DLL, DBMS_DESCRIBE, DBMS_JOB, DBMS_OUTPUT,DBMS_PIPE, DBMS_RANDOM, DBMS_REFRESH, DBMS_SHARED_POOL, DBMS_SQL, STANDARD, UTL_FILE (read and write text in OS Files), UTL_HTTP (HTTP Callouts from PL/SQL & SQL to access data),
www.accelfrontline.in
DBMS PACKAGESThe Oracle Database comes with a number of standard
packages. Most of these packages are only documented in the package specification. This page has extracted the introduction to this information on a single page.The packages will be documented in more detail and with specific explanation on he use of the functionality in the near future.
DBMS_ALERT This package provides support for asynchronous
database events without polling. By appropriate use of this package and database triggers, an application can cause itself to be notified whenever values of interest in the database are changed
www.accelfrontline.in
DBMS PACKAGES• DBMS_APPLICATION_INFO • The dbms_application_info package provides a
mechanism for registering the name of the application module that is currently running with the rdbms. Registering the name of the module allows DBAs to monitor how the system is being used, and do performance analysis, and resource accounting by module. The name that is registered through this package will appear in the 'module' and 'action' column of the v$session virtual table. It will also appear in the 'module' and 'action' columns in v$sqlarea.
www.accelfrontline.in
Contd..,DBMS_DDL This package provides access to some SQL
DDL statements from stored procedures.It also provides some special administration operations that are not available as DDLs.
DBMS_OUTPUT This package can be used to issue messages
from PL/SQL that showup in sql*dba and sql*plus with the 'set serveroutput on' command.
www.accelfrontline.in
Contd..,• DBMS_PIPE • This package provides a "pipe" service on
ddatabase level which allows messages to be sent between sessions through a software channel.
DBMS_SESSION This package provides access to SQL "alter
session" statements, and other session information from, stored procedures.
DBMS_SHARED_POOL This package provides access to the shared pool.
This is the shared memory area where cursors and PL/SQL objects are stored.
www.accelfrontline.in
Contd..,• DBMS_SPACE • This package provides segment
space information not currently available through the standard views.
• DBMS_SQL • This package provides a means to
use dynamic SQL to access the database.
www.accelfrontline.in
Contd..,• DBMS_TRANSACTION • This package provides access to SQL
transaction statements from stored procedures.It also provids functions for monitoring transaction activities (transaction ids and ordering of steps of transactions )