SQL-Note
-
Upload
amit-bansal -
Category
Documents
-
view
212 -
download
0
Transcript of SQL-Note
-
8/20/2019 SQL-Note
1/18
PL/SQL
PL/SQL stands for Procedural Language/SQL.PL/SQL extends SQL by adding control Structures found inother procedural language.PL/SQL combines the flexibility of SQL with Powerful feature of 3 rd
generation Language. The procedural construct and database access Are present in PL/SQL.PL/SQL canbe used in both in database in racle Ser!er and in "lient side application de!elopment tools.
Advantages of PL/SQL
Support for SQL# support for ob$ect%oriented programming## better performance# portability# higherproducti!ity# &ntegration with racle
a' Supports the declaration and manipulation of ob$ect types and collections.b' Allows the calling of external functions and procedures.c' "ontains new libraries of built in pac(ages.d' with PL/SQL # an multiple s)l statements can be processed in a single command line statement.
PL/SQL Datatypes
Scalar Types
*&+A,-&+T0, #1"#1"&2AL#1*L ##P,"&S&+#4LAT#&+T#&+T0,#+AT,AL#+AT,AL+#+2*,# +2,&"# PLS&+T0,#PS&T&5#PS&T&5+#,AL#S&0+T-P#S2ALL&+T#"6A,#"6A,A"T,#L+0#L+0 ,A7#+"6A,#+5A,"6A,8#,A7#,7&1#ST,&+0#5A,"6A,#5A,"6A,8# "omposite Types
TA*L# 5A,,A-# ,",1
L* Types*4&L# *L*# "L*# +"L*
,eference Types
,4 ",S,
*LA+# 1AT
1*2STPT.PTL&+9
&t is a pre%defined pac(age that prints the message inside the parenthesis
ANONYMOUS PL/SQL BLOCK.
The text of an Oracle Forms trigger is an anonymous PL/SQL block. It consists of three sections:
• !eclaration of "ariables# constants# cursors an! exce$tions %hich is o$tional.
• section of executable statements.
• section of exce$tion han!lers# %hich is o$tional.
ATTRIBUTES
Allow us to refer to data types and ob$ects from the database.PL/SQL !ariables and "onstants can ha!eattributes. The main ad!antage of using Attributes is e!en if you "hange the data definition# you don:tneed to change in the application.
%TYPE
&t is used when declaring !ariables that refer to the database columns.
sing ;T-P to declare !ariable has two ad!antages. 4irst# you need not (now the exact datatype of !ariable. Second# if the database definition of !ariable changes# the datatype of !ariable changesaccordingly at run time.
1
-
8/20/2019 SQL-Note
2/18
%ROWTYPE
The ;,7T-P attribute pro!ides a record type that represents a row in a table
-
8/20/2019 SQL-Note
3/18
3
-
8/20/2019 SQL-Note
4/18
Using SQLCODE and SQLERRM
4or internal exceptions# SQL"1 returns the number of the racle error. The number that SQL"1
returns is negati!e unless the racle error is no data found# in which case SQL"1 returns IJEE.SQL,,2 returns the corresponding error message. The message begins with the racle error code.
Unhandled Exceptions
PL/SQL returns an unhandled exception error to the host en!ironment# which determines the outcome.
When Others
&t is used when all exception are to be trapped.
CURSORS
racle allocates an area of memory (nown as context area for the processing of SQL statements. Thepointer that points to the context area is a cursor.
#e%!ts
J' Allowing to position at specific rows of the result set.8' ,eturning one row or bloc( of rows from the current position in the result set.3' Supporting data modification to the rows at the current position in the result set.
TYPES
&' STATIC CURSOR
SQL statement is determined at design time.
A] EXPLICIT CURSOR
2ultiple row SL"T statement is called as an explicit cursor.
To execute a multi%row )uery# racle opens an unnamed wor( area that stores processing
information. To access the information# you can use an explicit cursor# which names the wor(area.
sage % &f the SL"T statement returns more that one row then explicit cursor should beused.
Steps
• 1eclare a cursor
• pen a cursor
• 4etch data from the cursor
• "lose the cursor
@PL&"&T ",S, ATT,&*TS
• ;4+1
-
8/20/2019 SQL-Note
5/18
+1 LP? To refer an element of the record use Krecord name. Column name
Parameterized Cursor
A cursor can ta(e parameters# which can appear in the associated )uery where!er constants canappear. The formal parameters of a cursor must be &+ parameters. Therefore# they cannot return!alues to actual parameters. Also# you cannot impose the constraint +T +LL on a cursor parameter.
The !alues of cursor parameters are used by the associated )uery when the cursor is opened.
B .IMPLICIT CURSOR
An &2PL&"&T cursor is associated with any SQL 12L statement that does not ha!e a explicitcursor associated with it.
This includes:
• All &+S,T statements
• All P1AT statements
• All 1LT statements
• All SL"T .. &+T statements
&2PL&"&T ",S, ATT,&*TSM SQL;4+1
-
8/20/2019 SQL-Note
6/18
ORACLE ,I
Advaned Exp-!!t C.%so% Conepts
1. FOR UPDATE WAIT Clause
• Loc( the rows before the update or delete.
• se explicit loc(ing to deny access for the duration of a transaction.
Syntax
"ursor eipcJ is select O from emp for update of columnreference ' +7A&T '
"olumn ,eference &t is column in the table against which the )uery is performed
A list of column may also be used '
+7A&T ,eturns an racle rror if the rows are loc(ed by another session.
The SL"T... 4, P1AT statement has been modified to allow the user to specify howlong the command should wait if the rows being selected are loc(ed.
&f +7A&T is specified# then an error is returned immediately if the loc( cannot be obtained.
Exap-e of Us!ng +OR UPDATE 0AIT C-a.se
J. SL"T O 4,2 2PL-S 76, 1PA,T2+T&1 JE 4, P1AT 7A&T 8E?
8. 1"LA,",S, 2P",S, &SSL"T 2P+# +A2# 1+A2 4,2 2P#1PT 76,
2P.1PT+1PT.1PT+ A+1 2P.1PT++HE4, P1AT 4 SALA,- +7A&T?
Retrieve the Employees who work in department 80 and update their Salary ]
2. The WHERE CURRENT OF Clause
• se cursors to update or delete the cursor row.
• &nclude the 4, P1AT clause in the cursor )uery to loc( the row first.
• se the 76, ",,+T 4 clause to refer the current row from an explicit cursor.
Syntax76, ",,+T 4 K cursorname
"ursor+ame %&t is the name of a declared cursor. The cursor ha!e been
declared with the 4, P1AT clause'
Exap-e of Us!ng +OR 01ERE CURRENT O+ C-a.seJ. 1"LA,
",S, 2P",S, &S SL"T 2P+# +A2# 1+A2 4,2 .2P#1.1PT 76,2P.1PT+1PT.1PT+ A+1 2P.1PT++HE 4, P1AT 4 SALA,- +7A&T?
*0&+4, & &+ 2P",S,?
LP
&4 &.SALKREEE T6+
P1AT 2P ST SALA,-&.SALOJ.JE 76, ",,+T 4 2P",S,?
6
-
8/20/2019 SQL-Note
7/18
+1 &4?+1 LP?
+1?
The Eample loops throu!h ea"h employee in department 80 # and "he"ks whether the salary is
less than $000&' salary is less than # the salary is raised (y )0% The where "urrent o' "lause in the*P+,TE statement re'ers to the "urrently 'et"hed re"ords ]
3. CURSORS WITH SUB QUERIES
Sub )ueries are often used in the 76, clause of select statement. &t can be used to4,2 clause# creating a temporary data source for the )uery.
DECLAREbonus REAL;
BEGINFOR emp_rec IN (SELECT empno, sal, comm FRO emp!LOO"
bonus #$ (emp_rec%sal & '%'! ) (emp_rec%comm & '%*!;INSERT INTO bonuses +ALES (emp_rec%empno, bonus!;
END LOO";COIT;
END;
7
-
8/20/2019 SQL-Note
8/18
PROCEDURES
Procedure is a subprogram that contains set of SQL and PL/SQL statements.
Merits,eusability % Subprograms once executed can be used in any number of applications2aintainability % Subprogram can simplify maintenance# subprogram will be affected only
its definition changes
Parameter
&+ % The &+ parameter is used to pass !alues to a subprogram when it is in!o(edT % The T parameter is used to return !alues to the caller of a subprogram&+ T The &+ T parameter is used to pass initial !alues to the subprogram
when in!o(ed and also it returns updated !alues to the caller.
Using the NOCOPY Compiler Hint
Suppose a subprogram declares an &+ parameter# an T parameter# and an &+ T parameter. 7henyou call the subprogram# the &+ parameter is passed by reference. That is# a pointer to the &+ actualparameter is passed to the corresponding formal parameter. So# both parameters reference the samememory location# which holds the !alue of the actual parameter.
*y default# the T and &+ T parameters are passed by !alue. That is# the !alue of the &+ T
actual parameter is copied into the corresponding formal parameter. Then# if the subprogram exitsnormally# the !alues assigned to the T and &+ T formal parameters are copied into the
corresponding actual parameters.
7hen the parameters hold large data structures such as collections# records# and instances of ob$ect
types# all this copying slows down execution and uses up memory. To pre!ent that# you can specify the+"P- hint# which allows the PL/SQL compiler to pass T and &+ T parameters by reference.&n the following example# you as( the compiler to pass &+ T parameter mystaff by referenceinstead of by !alue9
DECLARET-"E S.a// IS +ARRA-(*''! OF Emplo0ee;"ROCEDRE reor1an23e (m0_s.a// IN OT NOCO"- S.a//! IS %%%
,emember# +"P- is a hint# not a directi!e. So# the compiler might pass mystaff by !alue despiteyour re)uest. sually# howe!er# +"P- succeeds. So# it can benefit any PL/SQL application that
passes around large data structures.
&n the example below# 8REEE records are loaded into a local nested table# which is passed to two localprocedures that do nothing but execute +LL statements. 6owe!er# a call to one procedure ta(es 8Jseconds because of all the copying. 7ith +"P-# a call to the other procedure ta(es much less than Jsecond.
S4L5 SET SER+EROT"T ONS4L5 GET .es.%s6l7 DECLARE* T-"E EmpTabT0p IS TABLE OF emp8RO9T-"E;: emp_.ab EmpTabT0p #$ EmpTabT0p(NLL!; 2n2.2al23e< .7 NBER(!; .* NBER(!;
= .: NBER(!;> "ROCEDRE 1e._.2me (. OT NBER! IS? BEGIN
SELECT TO_C@AR(S-SDATE,SSSSS! INTO . FRO ual;
8
-
8/20/2019 SQL-Note
9/18
-
8/20/2019 SQL-Note
10/18
+UNCTIONS
4unction is a subprogram that computes and returns a single !alue.A function is a subprogram that computes a !alue. 4unctions and procedures are structured ali(e#except that functions ha!e a ,T,+ clause.
FNCTION NAE K("ARAETERK, "ARAETER, %%%! RETRN DATAT-"E ISKLOCAL DECLARATIONSBEGIN
EECTABLE STATEENTSKECE"TION
ECE"TION @ANDLERS
A function has two parts9 the specification and the body. The function specification begins with the
(eyword 4+"T&+ and ends with the ,T,+ clause# which specifies the datatype of the result !alue.Parameter declarations are optional. 4unctions that ta(e no parameters are written withoutparentheses. The function body begins with the (eyword &S and ends with the (eyword +1 followed
by an optional function name.
Using the RETURN Statement
The ,T,+ statement immediately completes the execution of a subprogram and returns control to
the caller. xecution then resumes with the statement following the subprogram call.
-
8/20/2019 SQL-Note
11/18
!"#ro$ed #er%or"&nce
• "oi! re$arsing for multi$le users by ex$loiting the share! SQL area
• "oi! PL/SQL $arsing at run'time by $arsing at com$ile time
• (e!uce the number of calls to the !atabase an! !ecrease net%ork traffic by bun!ling comman!s
!"#ro$ed "&inten&nce.
• )o!ify routines online %ithout interfering %ith other users
• )o!ify one routine to affect multi$le a$$lications
• )o!ify one routine to eliminate !u$licate testing
!"#ro$ed d&t& securit' &nd inte(rit'• *ontrol in!irect access to !atabase ob+ects from non $ri"ilege! users %ith security $ri"ileges
• ,nsure that relate! actions are $erforme! together# or not at all# by funneling acti"ity for relate! tables
through a single $ath
L!ST ALL P)OC*+U)*S AN+ FUNCT!ONS
SELECT OBECT_NAE, OBECT_T-"E FRO SER_OBECTS 9@ERE OBECT_T-"E IN("ROCEDRE, FNCTION! ORDER B- OBECT_NAE
L!ST T,* CO+* OF P)OC*+U)*S AN+ FUNCT!ONS
SELECT TET FRO SER_SORCE 9@ERE NAE $ 4ER-_E" ORDER B- LINE;
PAC2A"E
A pac(age is a schema ob$ect that groups logically related PL/SQL types# items# and subprograms.Pac(ages usually ha!e two parts# a specification and a body#
Merits
Si"#li%' securit' -o nee! to issue (-T for e"ery $roce!ure in a $ackageLi"it reco"#il&tion *hange the bo!y of the $roce!ure or function %ithout changing s$ecificationPer%or"&nce First call to $ackage loa!s %hole $ackage into memory
!n%or"&tion ,idin( ith $ackages# you can s$ecify %hich ty$es# items# an! sub$rograms are$ublic 0"isible an! accessible1 or $ri"ate 0hi!!en an! inaccessible1.
,idin( Im$lementation !etails from users# you $rotect the integrity of the $ackage.
Parts of Package
A.PACKAGE SPECIFICATION
The pac(age specification contains public declarations. The scope of these declarations is local to yourdatabase schema and global to the pac(age. So# the declared items are accessible from your
application and from anywhere in the pac(age.
B.PACKAGE BODY
The pac(age body implements the pac(age specification. That is# the pac(age body contains thedefinition of e!ery cursor and subprogram declared in the pac(age specification. eep in mind thatsubprograms defined in a pac(age body are accessible outside the pac(age only if their specificationsalso appear in the pac(age specification.
PACKAGE OVERLOADING
PL/SQL allows two or more pac(aged subprograms to ha!e the same name. This option is useful whenyou want a subprogram to accept parameters that ha!e different datatypes.
PRIVATE VERSUS PUBLIC ITEMS
PR&-,TE The pac(age body can also contain pri!ate declarations# which define types and items necessary for the
internal wor(ings of the pac(age. The scope of these declarations is local to the pac(age body.
11
-
8/20/2019 SQL-Note
12/18
Therefore# the declared types and items are inaccessible except from within the pac(age body. nli(e apac(age spec# the declarati!e part of a pac(age body can contain subprogram bodies.
P*./& Such items are termed pu(li" . 7hen you must maintain items throughout a session or acrosstransactions# place them in the declarati!e part of the pac(age body.
Advantages of Packages
Pac(ages offer se!eral ad!antages9 modularity# easier application design# information hiding# addedfunctionality# and better performance.
#od.-a%!ty
Pac(ages let you encapsulate logically related types# items# and subprograms in a namedPL/SQL module. ach pac(age is easy to understand# and the interfaces between pac(ages aresimple# clear# and well defined. This aids application de!elopment.
Eas!e% App-!at!on Des!gn
7hen designing an application# all you need initially is the interface information in the pac(agespecs. -ou can code and compile a spec without its body. Then# stored subprograms thatreference the pac(age can be compiled as well. -ou need not define the pac(age bodies fully
until you are ready to complete the application.
Info%at!on 1!d!ng
7ith pac(ages# you can specify which types# items# and subprograms are public
accessible= or pri!ate
-
8/20/2019 SQL-Note
13/18
The global memory for such pac(ages is pooled in the System 0lobal Area
-
8/20/2019 SQL-Note
14/18
DATABASE TRI""ERS
Trigger !efines an action the !atabase shoul! take %hen some !atabase relate! e"ent occurs. Triggers may be
use! to su$$lement !eclarati"e referential integrity# to enforce com$lex business rules.
!atabase trigger is a store! sub$rogram associate! %ith a table. 2ou can ha"e Oracle automatically fire the trigger before or after an I-S,(T# 3P4T,# or 4,L,T, statement affects the table.
Triggers are execute! %hen a s$ecific !ata mani$ulation comman! are $erforme! on s$ecific tables
ROW LEVEL TRIGGERS
(o% Le"el triggers execute once for each ro% in a transaction. (o% le"el triggers are create using FO( ,*5 (Oclause in the create trigger comman!.
STATEMENT LEVEL TRIGGERS
Statement Le"el triggers execute once for each transaction. For exam$le if you insert 677 ro%s in a single transactionthen statement le"el trigger %ill be execute! once.
BEFORE and AFTER Triggers
Since triggers occur because of e"ents# they may be set to occur imme!iately before or after those e"ents.
The follo%ing table sho%s the number of triggers that you can ha"e for a table. The number of triggers you can ha"e afor a table is 68 triggers.
The follo%ing table sho%s the number of triggers that you can ha"e for a table. The number of triggers you can ha"e afor a table is 68 triggers.
ROW LEVEL TRIGGER STATEMENT LEVEL TRIGGER
BEFORE INSERT
UPDATE
DELETE
INSERT
UPDATE
DELETE
INSTEAD OF INSTEAD OF ROW
AFTER INSERT
UPDATE
DELETE
INSERT
UPDATE
DELETE
ADVANTAGES OF TRIGGERS
14
-
8/20/2019 SQL-Note
15/18
Fe&ture *nh&nce"ent
Security The Oracle Ser"er allo%s table access to users or roles. Triggers allo% table accessaccor!ing to !ata "alues.
Auditing The Oracle Ser"er tracks !ata o$erations on tables. Triggers track "alues for !atao$erations on tables.
Data integrity The Oracle Ser"er enforces integrity constraints. Triggers im$lement com$lex integrity
rules.
Referential integrity The Oracle Ser"er enforces stan!ar! referential integrity rules. Triggers im$lementnonstan!ar! functionality.
Table replication The Oracle Ser"er co$ies tables asynchronously into sna$shots. Triggers co$y tablesSynchronously into re$licas.
Derived data The Oracle Ser"er com$utes !eri"e! !ata "alues manually. Triggers com$ute !eri"e! !ata"alues automatically.
Event logging The Oracle Ser"er logs e"ents ex$licitly. Triggers log e"ents trans$arently.
Syntax:
CREATE OR RE"LACE TRIGGER TRIGGER NAE5 K BEFORE AFTER INSTEAD OF
(INSERT OR "DATE OR DELETE! ON TABLE NAE5 REFERENCING OLD AS OLD NE9 AS NE9 FOR
EAC@ RO9
BEGIN
END;
Example 1:
CREATE OR RE"LACE TRIGGER -_TRIG BEFORE INSERT OR "DATE OR DELETE ON
DETAIL FOR EAC@ RO9
BEGIN
IF LTRI(RTRI(TO_C@AR(S-SDATE,DA-!!!$FRIDA- T@EN
IF INSERTING T@EN
RAISE_A""LICATION_ERROR(*'''7,INSERT IS NOT "OSSIBLE!;
ELSIF "DATING T@EN
RAISE_A""LICATION_ERROR(*'''7,"DATE IS NOT "OSSIBLE!;
ELSIF DELETING T@EN
RAISE_A""LICATION_ERROR(*'''7,DELETE IS NOT "OSSIBLE!;
END IF;
END IF;
END;
Example 2:
CREATE OR RE"LACE TRIGGER -_TRIG AFTER INSERT ON
ITE FOR EAC@ RO9
15
-
8/20/2019 SQL-Note
16/18
-
8/20/2019 SQL-Note
17/18
CREATE OR RE"LACE TRIGGER TR' AFTER "DATE ON E"7''DECLARE
7 +ARC@AR*('!;BEGIN
SELECT SER INTO 7 FRO DAL;INSERT INTO SER7 +ALES(7,S-SDATE,"DATE!;
END;HS@O9 ERR
Example 8:
CREATE OR RE"LACE TRIGGER TR'= AFTER DELETE ON E"7''DECLARE7 +ARC@AR*('!;BEGINSELECT SER INTO 7 FRO DAL;INSERT INTO SER7 +ALES(7,S-SDATE,DELETE!;END;HS@O9 ERR
SYSTEM TRIGGER
LOGON and LOGOFF Trigger Example 2ou can create this trigger to monitor ho% often you log on an! off# or you may %ant to %rite a re$ort on ho% long youare logge! on for. If you %ere a 49 %anting to !o this# you %oul! re$lace S*5,) %ith 4T9S,.
7% CREATE OR RE"LACE TRIGGER LOGON_TRIGAFTER lo1on ON SC@EABEGIN
INSERT INTO lo1_.r21_.able (user_2, lo1_a.e, ac.2on! +ALES
(user, s0sa.e, Lo112n1 on!;END;
*% CREATE OR RE"LACE TRIGGER LOGOFF_TRIGBEFORE lo1o// ON SC@EABEGIN
INSERT INTO lo1_.r21_.able (user_2, lo1_a.e, ac.2on! +ALES(user, s0sa.e, Lo112n1 o//!;
END;
CALL STATEMENT
This allo%s you to call a store! $roce!ure# rather than co!ing the PL/SQL bo!y in the trigger itself.
CREATE KOR RE"LACE TRIGGER .r211er_name.2m2n1ePen.7 KOR ePen.* OR ePen.:ON .able_nameKREFERENCING OLD AS ol NE9 AS neQKFOR EAC@ RO9K9@EN con2.2onCALL proceure_name
CREATE TRIGGER TEST:
BEFORE INSERT ON E"CALL LOG_EECTION
INSTEAD OF TRIGGERS
17
-
8/20/2019 SQL-Note
18/18
&+STA1 4 triggers to tell ,A"L what to do instead of performing the actions that executedthe trigger. An &+STA1 4 trigger can be used for a !iew. These triggers can be used to o!ercome therestrictions placed by oracle on any !iew which is non updateable.
*-&"#le:
CREATE OR RE"LACE +IE9 E"_DE"T AS SELECT A%DE"TNO,B%E"NO FRO DE"T A,E" B9@ERE A%DE"TNO$B%DE"TNO
CREATE OR RE"LACE TRIGGER TRIG7 INSTEAD OF INSERT ON E"_DE"TREFERENCING NE9 AS N FOR EAC@ RO9BEGIN
INSERT INTO DE"T +ALES(#N%DE"TNO,DNAE!;INSERT INTO E" +ALES(#N%E"NO,ENAE,#N%DE"TNO!;
END;
18