0% found this document useful (0 votes)
268 views136 pages

PLSQL Full Notes1

The document provides information about data types available in Oracle/PLSQL including character, numeric, date/time, large object (LOB), rowid, and conditional statements. It lists the syntax and explanations for various data types such as char, number, date, blob, clob, rowid, and case statements. It also discusses using IS NULL and IS NOT NULL to check for null values in PLSQL code.

Uploaded by

SuneelTej
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
268 views136 pages

PLSQL Full Notes1

The document provides information about data types available in Oracle/PLSQL including character, numeric, date/time, large object (LOB), rowid, and conditional statements. It lists the syntax and explanations for various data types such as char, number, date, blob, clob, rowid, and case statements. It also discusses using IS NULL and IS NOT NULL to check for null values in PLSQL code.

Uploaded by

SuneelTej
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 136

Oracle/PLSQL: Data Types

The following is a list of datatypes available in Oracle.

Character Datatypes
Data Type Syntax char(size) nchar(size) Oracle 9i Maximum size of 2 bytes. Maximum size of 2 bytes. Oracle 10g Maximum size of 2 bytes. Maximum size of 2 bytes. Maximum size of ' bytes. Maximum size of ' bytes. Maximum size of 2)*. Maximum size of 2 bytes. Maximum size of 2)*. Oracle 11g Maximum size of 2 bytes. Maximum size of 2 bytes. Maximum size of ' bytes. Maximum size of ' bytes. Maximum size of 2)*. Maximum size of 2 bytes. Maximum size of 2)*. Explanation (i applica!le" !here size is the number of characters to store. "ixed#length strings. $pace padded. !here size is the number of characters to store. "ixed#length %&$ string $pace padded. !here size is the number of characters to store. (ariable#length %&$ string. !here size is the number of characters to store. (ariable#length string. (ariable#length strings. (bac+ward compatible) (ariable#length binary strings (ariable#length binary strings. (bac+ward compatible)

nvarchar2(size) Maximum size of ' bytes. varchar2(size) long raw long raw Maximum size of ' bytes. Maximum size of 2)*. Maximum size of 2 bytes. Maximum size of 2)*.

#$%eric Datatypes
Data Type Syntax Oracle 9i Oracle 10g Oracle 11g Explanation (i applica!le"

number(p,s)

-recision can range from . to /0. $cale can range from #0' to .21.

-recision can range from . to /0. $cale can range from #0' to .21.

-recision can range from !here p is the precision and s is the scale. . to /0. $cale can range from #0' "or example, number(1,2) is a number that has 2 digits before the decimal to .21. and 2 digits after the decimal.

numeric(p,s)

-recision can range from -recision can range from -recision can range from !here p is the precision and s is the scale. . to /0. . to /0. . to /0. "or example, numeric(1,2) is a number that has 2 digits before the decimal and 2 digits after the decimal.

float dec(p,s) -recision can range from -recision can range from -recision can range from !here p is the precision and s is the scale. . to /0. . to /0. . to /0. "or example, dec(/,.) is a number that has 2 digits before the decimal and . digit after the decimal. decimal(p,s) -recision can range from -recision can range from -recision can range from !here p is the precision and s is the scale. . to /0. . to /0. . to /0. "or example, decimal(/,.) is a number that has 2 digits before the decimal and . digit after the decimal. integer int smallint real double precision

Date/Ti%e Datatypes
Data Type Syntax date timestamp (fractional seconds precision) Oracle 9i Oracle 10g Oracle 11g Explanation (i applica!le"

3 date between 4an ., '1.2 *5 3 date between 4an ., '1.2 *5 3 date between 4an ., '1.2 *5 and 6ec /., 7777 36. and 6ec /., 7777 36. and 6ec /., 7777 36. fractional seconds precision must be a number between and 7. (default is 8) fractional seconds precision must be a number between and 7. (default is 8) fractional seconds precision must be a number between and 7. (default is 8) 9ncludes year, month, day, hour, minute, and seconds. "or example: timestamp(8)

timestamp (fractional seconds precision) with time zone

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

9ncludes year, month, day, hour, minute, and seconds; with a time zone displacement value. "or example: timestamp(2) with time zone

timestamp (fractional seconds precision) with local time zone

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

9ncludes year, month, day, hour, minute, and seconds; with a time zone expressed as the session time zone. "or example: timestamp(') with local time zone

interval year (year precision) to month interval day

year precision is the number of year precision is the number of year precision is the number of Time period stored in years and months. digits in the year. (default is 2) digits in the year. (default is 2) digits in the year. (default is 2) "or example: interval year(') to month day precision must be a day precision must be a day precision must be a Time period stored in days, hours, minutes,

(day precision) to second (fractional seconds precision)

number between (default is 2)

and 7.

number between (default is 2)

and 7.

number between (default is 2)

and 7.

and seconds. "or example: interval day(2) to second(8)

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

fractional seconds precision must be a number between and 7. (default is 8)

Large O!&ect (LO'" Datatypes


Data Type Syntax bfile Oracle 9i Oracle 10g Oracle 11g Explanation (i applica!le" "ile locators that point to a binary file on the server file system (outside the database). $tores unstructured binary large ob@ects. $tores single#byte and multi#byte character data. $tores unicode data.

Maximum file size of Maximum file size of 2/2#. bytes. ')*. $tore up to ')* of binary data. $tore up to ')* of character data. $tore up to ')* of character text data. $tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage). $tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage) of character data. $tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage) of character text data.

Maximum file size of 28'#. bytes.

blob clob

$tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage). $tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage) of character data. $tore up to (' gigabytes #.) < (the value of the 5=>%? parameter of &O* storage) of character text data.

nclob

(o)i* Datatypes
Data Type Syntax rowid Oracle 9i The format of the rowid is: *******.AAAA.""""" !here ******* is the bloc+ in the database file; AAAA is the row in the bloc+; """"" is the database file. urowid(size) Oracle 10g The format of the rowid is: *******.AAAA.""""" !here ******* is the bloc+ in the database file; AAAA is the row in the bloc+; """"" is the database file. Oracle 11g The format of the rowid is: *******.AAAA.""""" !here ******* is the bloc+ in the database file; AAAA is the row in the bloc+; """"" is the database file. >niversal rowid. !here size is optional.
5opyright C 2 /#2 7 Tech on the %et. 3ll rights reserved.

Explanation (i applica!le" "ixed#length binary data. Bvery record in the database has a physical address or ro)i*.

Oracle/PLSQL: Declaring +aria!les


The syntax for declaring variables is: ,aria!le-na%e .CO#ST/#T0 *atatype .#OT #1LL0 .:2 3 DE4/1LT initial-,al$e0

4or exa%ple: 6eclaring a variable:

LDescription ,archar5(60"7

6eclaring a constant: LTotal CO#ST/#T n$%eric(891" :2 8:;:9:6<17

6eclaring a variable with an initial value (not a constant): LType ,archar5(10" :2 =Exa%ple=7

Oracle/PLSQL: >S #OT #1LL


9n -&$D& to chec+ if a value is not null, you must use the E9$ %OT %>&&E syntax. "or example, >4 L,al$e >S #OT #1LL then <<< E#D >47 9f Lvalue does not contain a null value, the E9"E expression will evaluate to TA>B.

Fou can also use E9$ %OT %>&&E in an $D& statement. "or example:

select ? ro% s$ppliers )here s$pplier-na%e >S #OT #1LL7 This will return all records from the suppliers table where the supplier_name does not contain a null value.

Oracle/PLSQL: >S #1LL


9n -&$D& to chec+ if a value is null, you must use the E9$ %>&&E syntax. "or example, >4 L,al$e >S #1LL then <<< E#D >47 9f Lvalue contains a null value, the E9"E expression will evaluate to TA>B.

Fou can also use E9$ %>&&E in an $D& statement. "or example: select ? ro% s$ppliers )here s$pplier-na%e >S #1LL7 This will return all records from the suppliers table where the supplier_name contains a null value.

Oracle/PLSQL Topics: Loops an* Con*itional State%ents


>4@TAE#@ELSE State%ent

Case State%ent

BOTO State%ent Loop State%ent 4O( Loop C1(SO( 4O( Loop Chile Loop (epeat 1ntil Loop Exit State%ent

Oracle/PLSQL: >4@TAE#@ELSE State%ent


There are three different syntaxes for these types of statements. Syntax D1: >4@TAE# >4 con*ition TAE# E<<<state%ents<<<F E#D >47

Syntax D5: >4@TAE#@ELSE

>4 con*ition TAE# E<<<state%ents<<<F ELSE E<<<state%ents<<<F E#D >47

Syntax D:: >4@TAE#@ELS>4 >4 con*ition TAE# E<<<state%ents<<<F ELS>4 con*ition TAE# E<<<state%ents<<<F ELSE E<<<state%ents<<<F E#D >47

=ere is an example of a function that uses the 9"#T=B%#B&$B statement: C(E/TE O( (EPL/CE 4$nction >nco%eLe,el ( na%e-in ># ,archar5 " (ET1(# ,archar5 >S %onthly-,al$e n$%!er(;"7 >Le,el ,archar5(50"7 c$rsor c1 is select %onthly-inco%e ro% e%ployees )here na%e 2 na%e-in7 'EB>#

open c17 etch c1 into %onthly-,al$e7 close c17 >4 %onthly-,al$e G2 6000 TAE# >Le,el :2 =Lo) >nco%e=7 ELS>4 %onthly-,al$e H 6000 an* %onthly-,al$e G2 I000 TAE# >Le,el :2 =/,g >nco%e=7 ELS>4 %onthly-,al$e H I000 an* %onthly-,al$e G2 1J000 TAE# >Le,el :2 =Ko*erate >nco%e=7 ELSE >Le,el :2 =Aigh >nco%e=7 E#D >47 (ET1(# >Le,el7 E#D7 9n this example, weGve created a function called 9ncome&evel. 9t has one parameter called name_in and it returns a varchar2. The function will return the income level based on the employeeGs name.

Oracle/PLSQL: Case State%ent


$tarting in Oracle 7i, you can use the case statement within an $D& statement. 9t has the functionality of an 9"#T=B%#B&$B statement. The syntax for the case statement is: C/SE . expression 0 CAE# con*ition-1 TAE# res$lt-1 CAE# con*ition-5 TAE# res$lt-5

<<< CAE# con*ition-n TAE# res$lt-n ELSE res$lt E#D expression is optional. 9t is the value that you are comparing to the list of conditions. (ie: conditionH., conditionH2, ... conditionHn) condition_1 to condition_n must all be the same datatype. 5onditions are evaluated in the order listed. Once a condition is found to be true, the case statement will return the result and not evaluate the conditions any further. result_1 to result_n must all be the same datatype. This is the value returned once a condition is found to be true.

#ote: 9f no condition is found to be true, then the case statement will return the value in the B&$B clause. 9f the B&$B clause is omitted and no condition is found to be true, then the case statement will return %>&&. Fou can have up to 222 comparisons in a case statement. Bach !=B% ... T=B% clause is considered 2 comparisons.

/pplies To:

Oracle 7i, Oracle . g, Oracle ..g

4or exa%ple: Fou could use the case statement in an $D& statement as follows: (includes the expression clause)

select ta!le-na%e9 C/SE o)ner CAE# =SLS= TAE# =The o)ner is SLS= CAE# =SLSTEK= TAE# =The o)ner is SLSTEK= ELSE =The o)ner is another ,al$e= E#D ro% all-ta!les7 Or you could write the $D& statement using the case statement li+e this: (omits the expression clause) select ta!le-na%e9 C/SE CAE# o)ner2=SLS= TAE# =The o)ner is SLS= CAE# o)ner2=SLSTEK= TAE# =The o)ner is SLSTEK= ELSE =The o)ner is another ,al$e= E#D ro% all-ta!les7 The above two case statements are eIuivalent to the following 9"#T=B%#B&$B statement: >4 o)ner 2 =SLS= TAE# res$lt :2 =The o)ner is SLS=7 ELS>4 o)ner 2 =SLSTEK= TAE# res$lt :2 =The o)ner is SLSTEK==7 ELSE res$lt :2 =The o)ner is another ,al$e=7 E#D >47

The case statement will compare each owner value, one by one.

One thing to note is that the B&$B clause within the case statement is optional. Fou could have omitted it. &etGs ta+e a loo+ at the $D& statement above with the B&$B clause omitted. Four $D& statement would loo+ as follows: select ta!le-na%e9 C/SE o)ner CAE# =SLS= TAE# =The o)ner is SLS= CAE# =SLSTEK= TAE# =The o)ner is SLSTEK= E#D ro% all-ta!les7 !ith the B&$B clause omitted, if no condition was found to be true, the case statement would return %>&&.

4or Exa%ple: =ere is an example that demonstrates how to use the case statement to compare different conditions: select C/SE CAE# a G ! TAE# =hello= CAE# * G e TAE# =goo*!ye= E#D ro% s$ppliers7

4reM$ently /sNe* Q$estions

Q$estion: 5an you create a case statement that evaluates two different fieldsJ 9 want to return a value based on the combinations in two different fields. /ns)er: Fes, below is an example of a case statement that evaluates two different fields.

select s$pplier-i*9 C/SE CAE# s$pplier-na%e 2 =>'K= an* s$pplier-type 2 =Aar*)are= TAE# =#orth o ice= CAE# s$pplier-na%e 2 =>'K= an* s$pplier-type 2 =So t)are= TAE# =So$th o ice= E#D ro% s$ppliers7 $o if supplierHname field is IBM and the supplierHtype field is Hardware, then the case statement will return North office. 9f the supplierHname field is IBM and the supplierHtype is Software, the case statement will return South office.

Oracle/PLSQL: BOTO State%ent


The )OTO statement causes the code to branch to the label after the )OTO statement. "or example: BOTO la!el-na%e7

Then later in the code, you would place your label and code associated with that label. La!el-na%e: EstatementsF

Oracle/PLSQL: Loop State%ent


The syntax for the &OO- statement is: LOOP E<state%ents<F E#D LOOP7

Fou would use a &OO- statement when you are not sure how many times you want the loop body to execute and you want the loop body to execute at least once. The &OO- statement is terminated when it encounters either an BK9T statement or when it encounters an BK9T !=B% statement that evaluated to TA>B. &etGs ta+e a loo+ at an example: LOOP %onthly-,al$e :2 *aily-,al$e ? :17 EO>T CAE# %onthly-,al$e H 60007 E#D LOOP7 9n this example, the &OO- would terminate when the monthlyHvalue exceeded ' .

Oracle/PLSQL: 4O( Loop


The syntax for the "OA &oop is: 4O( loop-co$nter ># .(E+E(SE0 lo)est-n$%!er<<highest-n$%!er LOOP E<state%ents<F E#D LOOP7 Fou would use a "OA &oop when you want to execute the loop body a fixed number of times.

&etGs ta+e a loo+ at an example. 4O( Lcntr ># 1<<50 LOOP LCalc :2 Lcntr ? :17 E#D LOOP7 This example will loop 2 times. The counter will start at . and end at 2 .

The "OA &oop can also loop in reverse. "or example: 4O( Lcntr ># (E+E(SE 1<<1J LOOP LCalc :2 Lcntr ? :17 E#D LOOP7 This example will loop .2 times. The counter will start at .2 and end at .. (loops bac+wards)

Oracle/PLSQL: C1(SO( 4O( Loop


The syntax for the C !S"! #"! Loop is: 4O( recor*-in*ex in cursor_name LOOP E<state%ents<F E#D LOOP7 Fou would use a C !S"! #"! Loop when you want to fetch and process every record in a cursor. The C !S"! #"! Loop will terminate when all of the records in the cursor have been fetched. =ere is an example of a function that uses a C !S"! #"! Loop: C(E/TE O( (EPL/CE 4$nction Total>nco%e ( na%e-in ># ,archar5 " (ET1(# ,archar5 >S total-,al n$%!er(;"7 c$rsor c1 is select %onthly-inco%e ro% e%ployees )here na%e 2 na%e-in7

'EB># total-,al :2 07 4O( e%ployee-rec in c1 LOOP total-,al :2 total-,al P e%ployee-rec<%onthly-inco%e7 E#D LOOP7 (ET1(# total-,al7 E#D7 9n this example, weGve created a cursor called c.. The C !S"! #"! Loop will terminate after all records have been fetched from the cursor c..

Oracle/PLSQL: Chile Loop


The syntax for the !=9&B &oop is: CA>LE con*ition LOOP E<state%ents<F E#D LOOP7 Fou would use a !=9&B &oop when you are not sure how many times you will execute the loop body. $ince the !=9&B condition is evaluated before entering the loop, it is possible that the loop body may not execute even once. &etGs ta+e a loo+ at an example: CA>LE %onthly-,al$e G2 6000 LOOP %onthly-,al$e :2 *aily-,al$e ? :17 E#D LOOP7

9n this example, the !=9&B &oop would terminate once the monthlyHvalue exceeded '

Oracle/PLSQL: (epeat 1ntil Loop


Oracle doesnGt have a Aepeat >ntil loop, but you can emulate one. The syntax for emulating a AB-B3T >%T9& &oop is: LOOP E<state%ents<F EO>T CAE# !oolean-con*ition7 E#D LOOP7 Fou would use an emulated AB-B3T >%T9& &oop when you do not +now how many times you want the loop body to execute. The AB-B3T >%T9& &oop would terminate when a certain condition was met. &etGs ta+e a loo+ at an example: LOOP %onthly-,al$e :2 *aily-,al$e ? :17 EO>T CAE# %onthly-,al$e H 60007 E#D LOOP7 9n this example, the &OO- would repeat until the monthlyHvalue exceeded ' .

Oracle/PLSQL: Exit State%ent


The syntax for the BK9T statement is: EO>T .CAE# !oolean-con*ition07 The BK9T statement is most commonly used to terminate &OO- statements. &etGs ta+e a loo+ at an example:

LOOP %onthly-,al$e :2 *aily-,al$e ? :17 EO>T CAE# %onthly-,al$e H 60007 E#D LOOP7 9n this example, the &OO- would terminate when the monthlyHvalue exceeded ' .

Oracle/PLSQL: SeM$ences (/$ton$%!er"


9n Oracle, you can create an autonumber field by using seIuences. 3 seIuence is an ob@ect in Oracle that is used to generate a number seIuence. This can be useful when you need to create a uniIue number to act as a primary +ey. The syntax for a seIuence is: C(E/TE SEQ1E#CE seM$ence-na%e K>#+/L1E ,al$e K/O+/L1E ,al$e ST/(T C>TA ,al$e >#C(EKE#T 'L ,al$e C/CAE ,al$e7 "or example: C(E/TE SEQ1E#CE s$pplier-seM K>#+/L1E 1 K/O+/L1E 999999999999999999999999999 ST/(T C>TA 1 >#C(EKE#T 'L 1 C/CAE 507 This would create a seIuence ob@ect called supplier_se$. The first seIuence number that it would use is . and each subseIuent number would increment by . (ie: 2,/,',...L. 9t will cache up to 2 values for performance. 9f you omit the K/O+/L1E option, your seIuence will automatically default to:

K/O+/L1E 999999999999999999999999999 $o you can simplify your 5AB3TB $BD>B%5B command as follows: C(E/TE SEQ1E#CE s$pplier-seM K>#+/L1E 1 ST/(T C>TA 1 >#C(EKE#T 'L 1 C/CAE 507 %ow that youGve created a seIuence ob@ect to simulate an autonumber field, weGll cover how to retrieve a value from this seIuence ob@ect. To retrieve the next value in the seIuence order, you need to use nextval. "or example: s$pplier-seM<next,al This would retrieve the next value from supplier_se$. The nextval statement needs to be used in an $D& statement. "or example: >#SE(T >#TO s$ppliers (s$pplier-i*9 s$pplier-na%e" +/L1ES (s$pplier-seM<next,al9 =Qra t 4oo*s="7 This insert statement would insert a new record into the suppliers table. The supplier_id field would be assigned the next number from the supplier_se$ seIuence. The supplier_name field would be set to ?raft "oods.

4reM$ently /sNe* Q$estions

One common Iuestion about seIuences is: Q$estion: !hile creating a seIuence, what does cache and nocache options meanJ "or example, you could create a seIuence with a cache of 2 as follows:

C(E/TE SEQ1E#CE s$pplier-seM K>#+/L1E 1 ST/(T C>TA 1 >#C(EKE#T 'L 1 C/CAE 507

Or you could create the same seIuence with the nocache option: C(E/TE SEQ1E#CE s$pplier-seM K>#+/L1E 1 ST/(T C>TA 1 >#C(EKE#T 'L 1 #OC/CAE7

/ns)er: !ith respect to a seIuence, the cache option specifies how many seIuence values will be stored in memory for faster access. The downside of creating a seIuence with a cache is that if a system failure occurs, all cached seIuence values that have not be used, will be ElostE. This results in a EgapE in the assigned seIuence values. !hen the system comes bac+ up, Oracle will cache new numbers from where it left off in the seIuence, ignoring the so called ElostE seIuence values. %ote: To recover the lost seIuence values, you can always execute an 3&TBA $BD>B%5B command to reset the counter to the correct value. Nocache means that none of the seIuence values are stored in memory. This option may sacrifice some performance, however, you should not encounter a gap in the assigned seIuence values.

Q$estion: =ow do we set the &3$T(3&>B value in an Oracle $eIuenceJ /ns)er: Fou can change the &3$T(3&>B for an Oracle seIuence, by executing an 3&TBA $BD>B%5B command.

"or example, if the last value used by the Oracle seIuence was . commands. alter seM$ence seM-na%e incre%ent !y 1567 select seM-na%e<next,al ro% *$al7 alter seM$ence seM-na%e incre%ent !y 17 %ow, the next value to be served by the seIuence will be 222.

and you would li+e to reset the seIuence to serve 222 as the next value. Fou would execute the following

Oracle/PLSQL Topics: Transactions


Co%%it (oll!acN Set Transaction LocN Ta!le

Oracle/PLSQL: Co%%it
The syntax for the 5OMM9T statement is: COKK>T .CO(Q0 .COKKE#T text07 The 5ommit statement commits all changes for the current session. Once a commit is issued, other users will be able to see your changes.

Oracle/PLSQL: (oll!acN
The syntax for the AO&&*35? statement is: (OLL'/CQ .CO(Q0 .TO .S/+EPO>#T0 sa,epoint-na%e07 The Aollbac+ statement undoes all changes for the current session up to the savepoint specified. 9f no savepoint is specified, then all changes are undone.

Oracle/PLSQL: Set Transaction


There are three transaction control functions. These are: 1< 5< :< SET T(/#S/CT>O# (E/D O#LL7 SET T(/#S/CT>O# >SOL/T>O# LE+EL SE(>/L>R/'LE7 SET T(/#S/CT>O# 1SE (OLL'/CQ SEBKE#T na%e7

Oracle/PLSQL: LocN Ta!le


The syntax for a &oc+ table is:

LOCQ T/'LE ta!les ># locN-%o*e KODE .#OC/>T07 Ta!les is a comma#delimited list of tables. LocN-%o*e is one of: !"% SH&!' !"% '(CL SI)' SH&!' *+&,' SH&!' SH&!' !"% '(CL SI)' '(CL SI)'#oCait specifies that the database should not wait for a loc+ to be released.

Oracle/PLSQL Topics: C$rsors


3 c$rsor is a mechanism by which you can assign a name to a Eselect statementE and manipulate the information within that $D& statement. !eGve categorized cursors into the following topics: Declare a C$rsor OPE# State%ent 4ETCA State%ent CLOSE State%ent C$rsor /ttri!$tes (S4O1#D9 S#OT4O1#D9 etc"

SELECT 4O( 1PD/TE State%ent CAE(E C1((E#T O4 State%ent

5ursor Bxamples: Proce*$re that o$tp$ts a *yna%ic PLSQL c$rsor C$rsor )ithin a c$rsor C$rsor )ith ,aria!le in an T># CL/1SET

Oracle/PLSQL: Declare a C$rsor


3 cursor is a $B&B5T statement that is defined within the declaration section of your -&$D& code. !eGll ta+e a loo+ at three different syntaxes for cursors.

C$rsor )itho$t para%eters (si%plest"


The basic syntax for a cursor without parameters is: C1(SO( c$rsor-na%e >S SELECT-state%ent7

"or example, you could define a cursor called c. as below.

C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 The result set of this cursor is all courseHnumbers whose courseHname matches the variable called nameHin.

*elow is a function that uses this cursor. C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 close c17 (ET1(# cn$%!er7

E#D7

C$rsor )ith para%eters


The basic syntax for a cursor with parameters is: C1(SO( c$rsor-na%e (para%eter-list" >S SELECT-state%ent7

"or example, you could define a cursor called c2 as below. C1(SO( c5 (s$!&ect-i*-in ># ,archar5" >S SELECT co$rse-n$%!er ro% co$rses-t!l )here s$!&ect-i* 2 s$!&ect-i*-in7 The result set of this cursor is all courseHnumbers whose sub@ectHid matches the sub@ectHid passed to the cursor via the parameter.

C$rsor )ith ret$rn cla$se


The basic syntax for a cursor with a return clause is: C1(SO( c$rsor-na%e (ET1(# iel*S(OCTLPE >S SELECT-state%ent7

"or example, you could define a cursor called c/ as below. C1(SO( c: (ET1(# co$rses-t!lS(OCTLPE >S SELECT ? ro% co$rses-t!l )here s$!&ect 2 =Kathe%atics=7 The result set of this cursor is all columns from the courseHtbl where the sub@ect is Mathematics.

Oracle/PLSQL: OPE# State%ent


Once youGve declared your cursor, the next step is to open the cursor. The basic syntax to O-B% the cursor is: OPE# c$rsor-na%e7

"or example, you could open a cursor called c. with the following command: OPE# c17

*elow is a function that demonstrates how to use the O-B% statement: C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7

C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 close c17 (ET1(# cn$%!er7 E#D7

Oracle/PLSQL: 4ETCA State%ent


The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can be performed on the data. 3fter declaring and opening your cursor, the next step is to "BT5= the rows from your cursor. The basic syntax for a "BT5= statement is: 4ETCA c$rsor-na%e >#TO Glist o ,aria!lesH7

"or example, you could have a cursor defined as:

C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 The command that would be used to fetch the data from this cursor is: 4ETCA c1 into cn$%!er7 This would fetch the first courseHnumber into the variable called cnumber;

*elow is a function that demonstrates how to use the "BT5= statement. C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7

close c17 (ET1(# cn$%!er7 E#D7

Oracle/PLSQL: CLOSE State%ent


The final step of wor+ing with cursors is to close the cursor once you have finished using it. The basic syntax to 5&O$B the cursor is: CLOSE c$rsor-na%e7

"or example, you could close a cursor called c. with the following command: CLOSE c17

*elow is a function that demonstrates how to use the 5&O$B statement: C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S

SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 close c17 (ET1(# cn$%!er7 E#D7

Oracle/PLSQL: C$rsor /ttri!$tes


!hile dealing with cursors, you may need to determine the status of your cursor. The following is a list of the cursor attributes that you can use. /ttri!$te M9$O-B% M"O>%6 Explanation # Aeturns TA>B if the cursor is open, "3&$B if the cursor is closed. # Aeturns 9%(3&96H5>A$OA if cursor is declared, but not open; or if cursor has been closed. # Aeturns %>&& if cursor is open, but fetch has not been executed. # Aeturns TA>B if a successful fetch has been executed.

# Aeturns "3&$B if no row was returned. M%OT"O>%6 # Aeturns 9%(3&96H5>A$OA if cursor is declared, but not open; or if cursor has been closed. # Aeturn %>&& if cursor is open, but fetch has not been executed. # Aeturns "3&$B if a successful fetch has been executed. # Aeturns TA>B if no row was returned. MAO!5O>%T # Aeturns 9%(3&96H5>A$OA if cursor is declared, but not open; or if cursor has been closed. # Aeturns the number of rows fetched. # The AO!5O>%T attribute doesnGt give the real row count until you have iterated through the entire cursor. 9n other words, you shouldnGt rely on this attribute to tell you how many rows are in a cursor after it is opened.

*elow is an example of how you might use the M%OT"O>%6 attribute. C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7

'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 close c17 (ET1(# cn$%!er7 E#D7

Oracle/PLSQL: SELECT 4O( 1PD/TE State%ent


The Select 4or 1p*ate statement allows you to loc+ the records in the cursor result set. Fou are not reIuired to ma+e changes to the records in order to use this statement. The record loc+s are released when the next commit or rollbac+ statement is issued. The syntax for the Select 4or 1p*ate is: C1(SO( c$rsor-na%e >S select-state%ent 4O( 1PD/TE .o col$%n-list0 .#OC/>T07

"or example, you could use the Select 4or 1p*ate statement as follows: C1(SO( c1 >S

SELECT co$rse-n$%!er9 instr$ctor ro% co$rses-t!l 4O( 1PD/TE o instr$ctor7

9f you plan on updating or deleting records that have been referenced by a Select 4or 1p*ate statement, you can use the Chere C$rrent O statement.

Oracle/PLSQL: CAE(E C1((E#T O4 State%ent


9f you plan on updating or deleting records that have been referenced by a Select 4or 1p*ate statement, you can use the Chere C$rrent O statement. The syntax for the Chere C$rrent O statement is either: 1PD/TE ta!le-na%e SET set-cla$se CAE(E C1((E#T O4 c$rsor-na%e7 OA DELETE 4(OK ta!le-na%e CAE(E C1((E#T O4 c$rsor-na%e7

The !here 5urrent Of statement allows you to update or delete the record that was last fetched by the cursor.

1p*ating $sing the CAE(E C1((E#T O4 State%ent


=ere is an example where we are updating records using the Chere C$rrent O $tatement:

C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in 4O( 1PD/TE o instr$ctor7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 else 1PD/TE co$rses-t!l SET instr$ctor 2 =SK>TA= CAE(E C1((E#T O4 c17 COKK>T7 en* i 7 close c17 (ET1(# cn$%!er7 E#D7

Deleting $sing the CAE(E C1((E#T O4 State%ent


=ere is an example where we are deleting records using the Chere C$rrent O $tatement: C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 C1(SO( c1 >S SELECT co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in 4O( 1PD/TE o instr$ctor7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 else DELETE 4(OK co$rses-t!l CAE(E C1((E#T O4 c17 COKK>T7 en* i 7 close c17 (ET1(# cn$%!er7

E#D7

Oracle/PLSQL: Proce*$re that o$tp$ts a *yna%ic PLSQL c$rsor


Q$estion: 9n Oracle, 9 have a table called EwineE and a stored procedure that outputs a cursor based on the EwineE table. 9Gve created an =TM& "orm where the user can enter any combination of three values to retrieve results from the EwineE table. My problem is that 9 need a general EselectE statement that will wor+ no matter what value(s), the user enters. Exa%ple: parameterH.N E5hiantiE parameterH2N E. E parameterH/N wasnGt entered by the user but 9 have to use in the select statement. 3nd this is my problem. =ow to initialize this parameter to get all rows for column/J $B&B5T < "AOM wine !=BAB column. N parameterH. 3%6 column2 N parameterH2 3%6 column/ N parameterH/;. The output of my stored procedure must be a cursor.

/ns)er: To solve your problem, you will need to output a dynamic -&$D& cursor in Oracle. &etGs ta+e a loo+ at how we can do this. !eGve divided this process into / steps.

Step 1 @ Ta!le De inition


"irst, we need a table created in Oracle called EwineE. *elow is the create statement for the wine table.

create ta!le )ine ( col1 ,archar5(60"9 col5 ,archar5(60"9 col: ,archar5(60" "7 !eGve made this table definition very simple, for demonstration purposes.

Step 5 @ Create pacNage


%ext, weGve created a pac+age called Ewinep+gE that contains our cursor definition. This needs to be done so that we can use a cursor as an o$tp$t parameter in our stored procedure.

create or replace P/CQ/BE )inepNg >S /? De ine the (E4 C1(SO( type< ?/ TLPE )ine-type >S (E4 C1(SO( (ET1(# )ineS(OCTLPE7 E#D )inepNg7 This cursor will accept all fields from the EwineE table.

Step : @ Create store* proce*$re


Our final step is to create a stored procedure to return the cursor. 9t accepts three parameters (entered by the user on the =TM& "orm) and returns a cursor (c.) of type EwineHtypeE which was declared in $tep 2. The procedure will determine the appropriate cursor to return, based on the value(s) that have been entered by the user (input parameters).

create or replace proce*$re in*-)ine5 (col1-in in ,archar59 col5-in in ,archar59 col:-in in ,archar59 c1 o$t )inepNg<)ine-type" as 'EB># /? all col$%ns )ere entere* ?/ >4 (length(col1-in" H 0" an* (length(col5-in" H 0" an* (length(col:-in" H 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col1 2 col1-in an* )ine<col5 2 col5-in an* )ine<col: 2 col:-in7 /? col1 an* col5 )ere entere* ?/ ELS>4 (length(col1-in" H 0" an* (length(col5-in" H 0" an* (length(col:-in" 2 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col1 2 col1-in an* )ine<col5 2 col5-in7 /? col1 an* col: )ere entere* ?/ ELS>4 (length(col1-in" H 0" an* (length(col5-in" 2 0" an* (length(col:-in" H 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col1 2 col1-in an* )ine<col: 2 col:-in7

/? col5 an* col: )here entere* ?/ ELS>4 (length(col1-in" 2 0" an* (length(col5-in" H 0" an* (length(col:-in" H 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col5 2 col5-in an* )ine<col: 2 col:-in7 /? col1 )as entere* ?/ ELS>4 (length(col1-in" H 0" an* (length(col5-in" 2 0" an* (length(col:-in" 2 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col1 2 col1-in7 /? col5 )as entere* ?/ ELS>4 (length(col1-in" 2 0" an* (length(col5-in" H 0" an* (length(col:-in" 2 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col5 2 col5-in7 /? col: )as entere* ?/ ELS>4 (length(col1-in" 2 0" an* (length(col5-in" 2 0" an* (length(col:-in" H 0" TAE# OPE# c1 4O( select ? ro% )ine )here )ine<col: 2 col:-in7 E#D >47 E#D in*-)ine57

Oracle/PLSQL: C$rsor )ithin a c$rsor

Q$estion: 9n -$D&, 9 want to declare a cursor within cursor. The second cursor should use a value from the first cursor in the Ewhere clauseE. =ow can 9 do thisJ

/ns)er: *elow is an example of how to declare a cursor within a cursor. 9n this example, we have a cursor called .et_ta/les that retrieves the owner and tableHname values. These values are then used in a second cursor called .et_columns. create or replace proce*$re K1LT>PLE-C1(SO(S-P(OC is ,-o)ner ,archar5(60"7 ,-ta!le-na%e ,archar5(60"7 ,-col$%n-na%e ,archar5(100"7 /? 4irst c$rsor ?/ c$rsor get-ta!les is select *istinct t!l<o)ner9 t!l<ta!le-na%e ro% all-ta!les t!l )here t!l<o)ner 2 =SLSTEK=7 /? Secon* c$rsor ?/ c$rsor get-col$%ns is select *istinct col<col$%n-na%e ro% all-ta!-col$%ns col )here col<o)ner 2 ,-o)ner an* col<ta!le-na%e 2 ,-ta!le-na%e7 !egin @@ Open irst c$rsor open get-ta!les7 loop etch get-ta!les into ,-o)ner9 ,-ta!le-na%e7

open get-col$%ns7 loop etch get-col$%ns into ,-col$%n-na%e7 en* loop7 close get-col$%ns7 en* loop7 close get-ta!les7 EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 en* K1LT>PLE-C1(SO(S-P(OC7

The tric+ to declaring a cursor within a cursor is that you need to continue to open and close the second cursor each time a new record is retrieved from the first cursor. That way, the second cursor will use the new variable values from the first cursor.

Oracle/PLSQL: C$rsor )ith ,aria!le in an T># CL/1SET


Q$estion: 9Gm trying to use a variable in an 9% 5&3>$B. /ss$%ptions U *eclarations: .. 2. /. '. AefHcursor is of type AB" 5>A$OA declared in -ac+age 9 will to pass a comma separated %umbers as a string This should be used in the Iuery in the 9% 5lause Bxecute the Duery and Aeturn the Output as AB" 5ursor

$omething similar to the following:

5reate or Aeplace "unction funcHname (in%umbers in (archar2) Aeturn -ac+age%ame.refHcursor 3s outHcursor -ac+age%ame.AefHcursor; *egin Open outHcursor "or $elect < from TableHname where columnHname in (in%umbers); Aeturn outHcursor; Bnd; 9 seem to be getting an error when 9 try the code above. =ow can 9 use a variable in an 9% 5&3>$BJ

/ns)er: >nfortunately, there is no easy way to use a variable in an 9% 5&3>$B if the variable contains a list of items. !e can, however, suggest two alternative options:

Option D1
9nstead of creating a string variable that contains a list of numbers, you could try storing each value in a separate variable. "or example: Create or (eplace 4$nction $nc-na%e (et$rn PacNage#a%e<re -c$rsor /s o$t-c$rsor PacNage#a%e<(e -c$rsor7 ,1 ,archar(5"7 ,5 ,archar(5"7 ,: ,archar(5"7 'egin

,1 :2 =1=7 ,5 :2 =5=7 ,: :2 =:=7 Open o$t-c$rsor 4or Select ? ro% Ta!le-na%e )here col$%n-na%e in (,19 ,59 ,:"7 (et$rn o$t-c$rsor7 En*7

Option D5
Fou could try storing your values in a table. Then use a sub#select to retrieve the values. "or example: Create or (eplace 4$nction $nc-na%e (et$rn PacNage#a%e<re -c$rsor /s o$t-c$rsor PacNage#a%e<(e -c$rsor7 'egin Open o$t-c$rsor 4or Select ? ro% Ta!le-na%e )here col$%n-na%e in (select ,al$es ro% list-ta!le"7 (et$rn o$t-c$rsor7 En*7 9n this example, weGve stored our list in a table called list_ta/le.

Oracle/PLSQL Topics: '$ilt@>n 4$nctions ('y Category"


+ie) an /lpha!etical Listing o 4$nctions 5haracter O $tring "unctions: /scii /sciiStr Chr Co%pose Concat Concat )ith 33 5onversion "unctions: 'in-To-#$% Cast CharTo(o)i* 4ro%-TV AexTo(a) 3dvanced "unctions: '4ilena%e Car*inality Case State%ent Coalesce Deco*e Mathematical "unctions: /!s /cos /sin /tan /tan5 /,g 'in-To-#$% 'it/n* Ceil Corr

Con,ert Deco%pose D$%p >nitcap >nstr Length #$%ToDS>nter,al #$%ToLK>nter,al (a)ToAex To-Char To-Clo! Bro$p->D Lag Lea* L##+L #/#+L Co,ar-pop Co,ar-sa%p Co$nt C$%e-Dist Dense-(anN Exp Extract 4loor Breatest Least

Lo)er Lpa* Ltri% (eplace (pa* (tri% To-Date To-DS>nter,al To-Lo! To-K$lti-'yte To-#Clo! #1LL>4 #+L #+L5 Sys-Context 1i* Kax Ke*ian Kin Ko* Po)er (anN (e%ain*er (o$n* (n$%!ers" (o$n* (*ates" Sign

So$n*ex S$!str Translate Tri% 1pper +SiVe To-#$%!er To-Single-'yte To-Ti%esta%p To-Ti%esta%p-TV To-LK>nter,al 1ser 1serEn,

SMrt St*De, S$% Tan Tanh Tr$nc (n$%!ers" Tr$nc (*ates" +ar-pop +ar-sa%p +ariance

Cos Cosh 6ate "unctions: /**-Konths C$rrent-Date C$rrent-Ti%esta%p D!Ti%eRone 4ro%-TV Brror "unctions: SQLCODE SQLE((K

Ln Log Last-Day LocalTi%esta%p Konths-'et)een #e)-Ti%e #ext-Day

Sin Sinh (o$n* SessionTi%eRone Sys*ate SysTi%esta%p To-Char To-Date Tr$nc TV-O set

Miscellaneous "unctions: (etrie,e $ser >D ro% the c$rrent Oracle session (etrie,e the session >D or the $ser logge* in

Oracle/PLSQL: Oracle Syste% Ta!les


*elow is an alphabetical listing of the Oracle system tables that are commonly used. Syste% Ta!le 3&&H3A)>MB%T$ 3&&H53T3&O) 3&&H5O&H5OMMB%T$ 3&&H5O%$TA39%T$ 3&&H5O%$H5O&>M%$ Description 3rguments in ob@ect accessible to the user 3ll tables, views, synonyms, seIuences accessible to the user 5omments on columns of accessible tables and views 5onstraint definitions on accessible tables 9nformation about accessible columns in constraint definitions

3&&H6*H&9%?$ 3&&HBAAOA$ 3&&H9%6BKB$ 3&&H9%6H5O&>M%$ 3&&H&O*$ 3&&HO*4B5T$ 3&&HO*4B5THT3*&B$ 3&&H$BD>B%5B$ 3&&H$%3-$=OT$ 3&&H$O>A5B 3&&H$F%O%FM$ 3&&HT3*&B$ 3&&HT3*H5O&>M%$ 3&&HT3*H5O&H$T3T9$T95$ 3&&HT3*H5OMMB%T$ 3&&HTA9))BA$ 3&&HTA9))BAH5O&$ 3&&HTF-B$ 3&&H>-63T3*&BH5O&>M%$ 3&&H>$BA$ 3&&H(9B!$

6atabase lin+s accessible to the user 5urrent errors on stored ob@ects that user is allowed to create 6escriptions of indexes on tables accessible to the user 5O&>M%s comprising 9%6BKes on accessible T3*&B$ 6escription of &O*s contained in tables accessible to the user Ob@ects accessible to the user 6escription of all ob@ect tables accessible to the user 6escription of $BD>B%5Bs accessible to the user $napshots the user can access 5urrent source on stored ob@ects that user is allowed to create 3ll synonyms accessible to the user 6escription of relational tables accessible to the user 5olumns of userGs tables, views and clusters 5olumns of userGs tables, views and clusters 5omments on tables and views accessible to the user Triggers accessible to the current user 5olumn usage in userGs triggers or in triggers on userGs tables 6escription of types accessible to the user 6escription of all updatable columns 9nformation about all users of the database 6escription of views accessible to the user

63T3*3$BH5OM-3T9*&BH&B(B& 6*3H6*H&9%?$ 6*3HBAAOA$ 6*3HO*4B5T$ 6*3HAO&B$ 6*3HAO&BH-A9($ 6*3H$O>A5B 6*3HT3*&B$-35B$ 6*3HT3*H-A9($ 6*3HTA9))BA$ 6*3HT$HD>OT3$ 6*3H>$BA$ 6*3H(9B!$ 695T9O%3AF 695TH5O&>M%$ )&O*3&H%3MB %&$H63T3*3$BH-3A3MBTBA$ %&$H9%$T3%5BH-3A3MBTBA$ %&$H$B$$9O%H-3A3MBTBA$

6atabase compatible parameter set via init.ora 3ll database lin+s in the database 5urrent errors on all stored ob@ects in the database 3ll ob@ects in the database 3ll Aoles which exist in the database Aoles granted to users and roles $ource of all stored ob@ects in the database 6escription of all tablespaces 3ll grants on ob@ects in the database 3ll triggers in the database Tablespace Iuotas for all users 9nformation about all users of the database 6escription of all views in the database 6escription of data dictionary tables and views 6escription of columns in data dictionary tables and views global database name -ermanent %&$ parameters of the database %&$ parameters of the instance %&$ parameters of the user session

-AO6>5TH5OM-O%B%TH(BA$9O% version and status information for component products AO&BHT3*H-A9($ Table privileges granted to roles

$B$$9O%H-A9($ $B$$9O%HAO&B$ $F$TBMH-A9(9&B)BHM3T3*&BH-A9(9&B)B$ T3*&BH-A9(9&B)BHM3-

-rivileges which the user currently has set Aoles which the user currently has enabled. 6escription table for privilege type codes. Maps privilege type numbers to type names )rants on ob@ects for which the user is the grantor, grantee, owner, or an enabled role or ->*&95 is the grantee 6escription table for privilege (auditing option) type codes. Maps privilege (auditing option) type numbers to type names

Oracle/PLSQL: Pri%ary Qeys


Chat is a pri%ary NeyW
3 pri%ary Ney is a single field or combination of fields that uniIuely defines a record. %one of the fields that are part of the primary +ey can contain a null value. 3 table can have only one primary +ey. #ote: 9n Oracle, a primary +ey can not contain more than /2 columns. 3 primary +ey can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a primary +ey using a 5AB3TB T3*&B statement is:

C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9 col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T constraint-na%e P(>K/(L QEL (col$%n19 col$%n59 < col$%n-n" "7

4or exa%ple: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 9n this example, weGve created a primary +ey on the supplier table called supplierHp+. 9t consists of only one field # the supplierHid field.

!e could also create a primary +ey with more than one field as in the example below: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*9 s$pplier-na%e" "7

1sing an /LTE( T/'LE state%ent


The syntax for creating a primary +ey in an 3&TBA T3*&B statement is:

/LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e P(>K/(L QEL (col$%n19 col$%n59 <<< col$%n-n"7

4or exa%ple: /LTE( T/'LE s$pplier a** CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*"7 9n this example, weGve created a primary +ey on the existing supplier table called supplierHp+. 9t consists of the field called supplierHid.

!e could also create a primary +ey with more than one field as in the example below: /LTE( T/'LE s$pplier a** CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*9 s$pplier-na%e"7

Drop a Pri%ary Qey


The syntax for dropping a primary +ey is: /LTE( T/'LE ta!le-na%e *rop CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$pplier *rop CO#ST(/>#T s$pplier-pN7

9n this example, weGre dropping a primary +ey on the supplier table called supplierHp+.

Disa!le a Pri%ary Qey


The syntax for disabling a primary +ey is: /LTE( T/'LE ta!le-na%e *isa!le CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$pplier *isa!le CO#ST(/>#T s$pplier-pN7 9n this example, weGre disabling a primary +ey on the supplier table called supplierHp+.

Ena!le a Pri%ary Qey


The syntax for enabling a primary +ey is: /LTE( T/'LE ta!le-na%e ena!le CO#ST(/>#T constraint-na%e7

4or exa%ple:

/LTE( T/'LE s$pplier ena!le CO#ST(/>#T s$pplier-pN7 9n this example, weGre enabling a primary +ey on the supplier table called supplierHp+.

Oracle/PLSQL Topics: 4oreign Qeys


5reating "oreign ?eys: 4oreign Qeys 4oreign Qeys )ith casca*e *elete 4oreign Qeys )ith Tset n$ll on *eleteT 6ropping "oreign ?eys: Drop a oreign Ney 6isableOBnable "oreign ?eys: Disa!le a oreign Ney Ena!le a oreign Ney

Oracle/PLSQL: 4oreign Qeys


Chat is a oreign NeyW
3 oreign Ney means that values in one table must also appear in another table.

The referenced table is called the parent ta!le while the table with the foreign +ey is called the chil* ta!le. The foreign +ey in the child table will generally reference a pri%ary Ney in the parent table. 3 foreign +ey can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a foreign +ey using a 5AB3TB T3*&B statement is: C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9 col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T N-col$%n 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n" "7

4or exa%ple: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" s$pplier-i* n$%eric(10" CO#ST(/>#T N-s$pplier

not n$ll9 not n$ll9

4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field.

!e could also create a foreign +ey with more than one field as in the example below: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*9 s$pplier-na%e" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" not n$ll9 s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 CO#ST(/>#T N-s$pplier-co%p 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e" "7 9n this example, our foreign +ey called f0_forei.n_comp references the supplier table based on two fields # the supplierHid and supplierHname fields.

1sing an /LTE( T/'LE state%ent


The syntax for creating a foreign +ey in an 3&TBA T3*&B statement is:

/LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n"7

4or exa%ple: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*"7 9n this example, weGve created a foreign +ey called f0_supplier that references the supplier table based on the supplierHid field.

!e could also create a foreign +ey with more than one field as in the example below: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e"7

Oracle/PLSQL: 4oreign Qeys )ith casca*e *elete


Chat is a oreign NeyW
3 oreign Ney means that values in one table must also appear in another table. The referenced table is called the parent ta!le while the table with the foreign +ey is called the chil* ta!le. The foreign +ey in the child table will generally reference a pri%ary Ney in the parent table.

3 foreign +ey with a 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. 3 foreign +ey with a cascade delete can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a foreign +ey using a 5AB3TB T3*&B statement is: C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9 col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T N-col$%n 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n" O# DELETE C/SC/DE "7

4or exa%ple: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" s$pplier-i* n$%eric(10"

not n$ll9 not n$ll9

CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" O# DELETE C/SC/DE "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field. *ecause of the cascade delete, when a record in the supplier table is deleted, all records in the products table will also be deleted that have the same supplierHid value.

!e could also create a foreign +ey (with a cascade delete) with more than one field as in the example below: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*9 s$pplier-na%e" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" not n$ll9 s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 CO#ST(/>#T N-s$pplier-co%p 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e" O# DELETE C/SC/DE "7 9n this example, our foreign +ey called f0_forei.n_comp references the supplier table based on two fields # the supplierHid and supplierHname fields.

The cascade delete on the foreign +ey called f0_forei.n_comp causes all corresponding records in the products table to be cascade deleted when a record in the supplier table is deleted, based on supplierHid and supplierHname.

1sing an /LTE( T/'LE state%ent


The syntax for creating a foreign +ey in an 3&TBA T3*&B statement is: /LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n" O# DELETE C/SC/DE7

4or exa%ple: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" O# DELETE C/SC/DE7 9n this example, weGve created a foreign +ey (with a cascade delete) called f0_supplier that references the supplier table based on the supplierHid field.

!e could also create a foreign +ey (with a cascade delete) with more than one field as in the example below: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e" O# DELETE C/SC/DE7

Oracle/PLSQL: 4oreign Qeys )ith Tset n$ll on *eleteT


Chat is a oreign NeyW
3 oreign Ney means that values in one table must also appear in another table. The referenced table is called the parent ta!le while the table with the foreign +ey is called the chil* ta!le. The foreign +ey in the child table will generally reference a pri%ary Ney in the parent table. 3 foreign +ey with a Eset null on deleteE means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign +ey fields set to null. The records in the child table will not be deleted. 3 foreign +ey with a Eset null on deleteE can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a foreign +ey using a 5AB3TB T3*&B statement is: C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9 col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T N-col$%n 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n" O# DELETE SET #1LL "7

4or exa%ple:

C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" not n$ll9 s$pplier-i* n$%eric(10"9 CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" O# DELETE SET #1LL "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field. *ecause of the set null on delete, when a record in the supplier table is deleted, all corresponding records in the products table will have the supplierHid values set to null.

!e could also create a foreign +ey Eset null on deleteE with more than one field as in the example below: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*9 s$pplier-na%e" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" s$pplier-i* n$%eric(10"9

not n$ll9

s$pplier-na%e ,archar5(J0"9 CO#ST(/>#T N-s$pplier-co%p 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e" O# DELETE SET #1LL "7 9n this example, our foreign +ey called f0_forei.n_comp references the supplier table based on two fields # the supplierHid and supplierHname fields. The delete on the foreign +ey called f0_forei.n_comp causes all corresponding records in the products table to have the supplierHid and supplierHname fields set to null when a record in the supplier table is deleted, based on supplierHid and supplierHname.

1sing an /LTE( T/'LE state%ent


The syntax for creating a foreign +ey in an 3&TBA T3*&B statement is: /LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e 4O(E>B# QEL (col$%n19 col$%n59 <<< col$%n-n" (E4E(E#CES parent-ta!le (col$%n19 col$%n59 <<< col$%n-n" O# DELETE SET #1LL7

4or exa%ple: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" O# DELETE SET #1LL7 9n this example, weGve created a foreign +ey Ewith a set null on deleteE called f0_supplier that references the supplier table based on the supplierHid field.

!e could also create a foreign +ey Ewith a set null on deleteE with more than one field as in the example below: /LTE( T/'LE pro*$cts a** CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*9 s$pplier-na%e" (E4E(E#CES s$pplier(s$pplier-i*9 s$pplier-na%e" O# DELETE SET #1LL7

Oracle/PLSQL: Drop a oreign Ney


The syntax for dropping a foreign +ey is: /LTE( T/'LE ta!le-na%e *rop CO#ST(/>#T constraint-na%e7

4or exa%ple: 9f you had created a foreign +ey as follows: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" s$pplier-i* n$%eric(10"

not n$ll9 not n$ll9

CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field.

9f we then wanted to drop the foreign +ey called f+Hsupplier, we could execute the following command: /LTE( T/'LE pro*$cts *rop CO#ST(/>#T N-s$pplier7

Oracle/PLSQL: Disa!le a oreign Ney


The syntax for disabling a foreign +ey is: /LTE( T/'LE ta!le-na%e *isa!le CO#ST(/>#T constraint-na%e7

4or exa%ple: 9f you had created a foreign +ey as follows: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*"

"7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" not n$ll9 s$pplier-i* n$%eric(10" not n$ll9 CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field.

9f we then wanted to disable the foreign +ey called f+Hsupplier, we could execute the following command: /LTE( T/'LE pro*$cts *isa!le CO#ST(/>#T N-s$pplier7

Oracle/PLSQL: Ena!le a oreign Ney


The syntax for enabling a foreign +ey is: /LTE( T/'LE ta!le-na%e ena!le CO#ST(/>#T constraint-na%e7

4or exa%ple: 9f you had created a foreign +ey as follows:

C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-pN P(>K/(L QEL (s$pplier-i*" "7 C(E/TE T/'LE pro*$cts ( pro*$ct-i* n$%eric(10" not n$ll9 s$pplier-i* n$%eric(10" not n$ll9 CO#ST(/>#T N-s$pplier 4O(E>B# QEL (s$pplier-i*" (E4E(E#CES s$pplier(s$pplier-i*" "7 9n this example, weGve created a primary +ey on the supplier table called supplier_p0. 9t consists of only one field # the supplierHid field. Then weGve created a foreign +ey called f0_supplier on the products table that references the supplier table based on the supplierHid field.

9f the foreign +ey had been *isa!le* and we wanted to enable it, we could execute the following command: /LTE( T/'LE pro*$cts ena!le CO#ST(/>#T N-s$pplier7

Oracle/PLSQL: 1niM$e Constraints


Chat is a $niM$e constraintW
3 $niM$e constraint is a single field or combination of fields that uniIuely defines a record. $ome of the fields can contain null values as long as the combination of values is uniIue. #ote:

9n Oracle, a uniIue constraint can not contain more than /2 columns. 3 uniIue constraint can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

Chat is the *i erence !et)een a $niM$e constraint an* a pri%ary NeyW


Pri%ary Qey %one of the fields that are part of the primary +ey can contain a null value. 1niM$e Constraint $ome of the fields that are part of the uniIue constraint can contain null values as long as the combination of values is uniIue.

Oracle does not permit you to create both a primary +ey and uniIue constraint with the same columns.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a uniIue constraint using a 5AB3TB T3*&B statement is: C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9

col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T constraint-na%e 1#>Q1E (col$%n19 col$%n59 < col$%n-n" "7

4or exa%ple: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-$niM$e 1#>Q1E (s$pplier-i*" "7 9n this example, weGve created a uniIue constraint on the supplier table called supplierHuniIue. 9t consists of only one field # the supplierHid field.

!e could also create a uniIue constraint with more than one field as in the example below: C(E/TE T/'LE s$pplier ( s$pplier-i* n$%eric(10" not n$ll9 s$pplier-na%e ,archar5(J0" not n$ll9 contact-na%e ,archar5(J0"9 CO#ST(/>#T s$pplier-$niM$e 1#>Q1E (s$pplier-i*9 s$pplier-na%e" "7

1sing an /LTE( T/'LE state%ent


The syntax for creating a uniIue constraint in an 3&TBA T3*&B statement is:

/LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e 1#>Q1E (col$%n19 col$%n59 <<< col$%n-n"7

4or exa%ple: /LTE( T/'LE s$pplier a** CO#ST(/>#T s$pplier-$niM$e 1#>Q1E (s$pplier-i*"7 9n this example, weGve created a uniIue constraint on the existing supplier table called supplierHuniIue. 9t consists of the field called supplierHid.

!e could also create a uniIue constraint with more than one field as in the example below: /LTE( T/'LE s$pplier a** CO#ST(/>#T s$pplier-$niM$e 1#>Q1E (s$pplier-i*9 s$pplier-na%e"7

Drop a 1niM$e Constraint


The syntax for dropping a uniIue constraint is: /LTE( T/'LE ta!le-na%e *rop CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$pplier *rop CO#ST(/>#T s$pplier-$niM$e7

9n this example, weGre dropping a uniIue constraint on the supplier table called supplierHuniIue.

Disa!le a 1niM$e Constraint


The syntax for disabling a uniIue constraint is: /LTE( T/'LE ta!le-na%e *isa!le CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$pplier *isa!le CO#ST(/>#T s$pplier-$niM$e7 9n this example, weGre disabling a uniIue constraint on the supplier table called supplierHuniIue.

Ena!le a 1niM$e Constraint


The syntax for enabling a uniIue constraint is: /LTE( T/'LE ta!le-na%e ena!le CO#ST(/>#T constraint-na%e7

4or exa%ple:

/LTE( T/'LE s$pplier ena!le CO#ST(/>#T s$pplier-$niM$e7 9n this example, weGre enabling a uniIue constraint on the supplier table called supplierHuniIue.

Oracle/PLSQL: ChecN Constraints


Chat is a checN constraintW
3 checN constraint allows you to specify a condition on each row in a table. #ote:

3 chec+ constraint can %OT be defined on a +>EC. The chec+ constraint defined on a table must refer to only columns in that table. 9t can not refer to columns in other tables. 3 chec+ constraint can %OT include a S1'Q1E(L.

3 chec+ constraint can be defined in either a 5AB3TB T3*&B statement or an 3&TBA T3*&B statement.

1sing a C(E/TE T/'LE state%ent


The syntax for creating a chec+ constraint using a 5AB3TB T3*&B statement is: C(E/TE T/'LE ta!le-na%e (col$%n1 *atatype n$ll/not n$ll9 col$%n5 *atatype n$ll/not n$ll9 <<< CO#ST(/>#T constraint-na%e CAECQ (col$%n-na%e con*ition" .D>S/'LE0 "7

The 69$3*&B +eyword is optional. 9f you create a chec+ constraint using the 69$3*&B +eyword, the constraint will be created, but the condition will not be enforced.

4or exa%ple: C(E/TE T/'LE s$ppliers ( s$pplier-i* n$%eric(6"9 s$pplier-na%e ,archar5(J0"9 CO#ST(/>#T checN-s$pplier-i* CAECQ (s$pplier-i* 'ETCEE# 100 an* 9999" "7 9n this first example, weGve created a chec+ constraint on the suppliers table called chec+HsupplierHid. This constraint ensures that the supplierHid field contains values between . and 7777.

C(E/TE T/'LE s$ppliers ( s$pplier-i* n$%eric(6"9 s$pplier-na%e ,archar5(J0"9 CO#ST(/>#T checN-s$pplier-na%e CAECQ (s$pplier-na%e 2 $pper(s$pplier-na%e"" "7 9n this second example, weGve created a chec+ constraint called chec+HsupplierHname. This constraint ensures that the supplierHname column always contains uppercase characters.

1sing an /LTE( T/'LE state%ent


The syntax for creating a chec+ constraint in an 3&TBA T3*&B statement is:

/LTE( T/'LE ta!le-na%e a** CO#ST(/>#T constraint-na%e CAECQ (col$%n-na%e con*ition" .D>S/'LE07 The 69$3*&B +eyword is optional. 9f you create a chec+ constraint using the 69$3*&B +eyword, the constraint will be created, but the condition will not be enforced.

4or exa%ple: /LTE( T/'LE s$ppliers a** CO#ST(/>#T checN-s$pplier-na%e CAECQ (s$pplier-na%e ># (=>'K=9 =Kicroso t=9 =#+>D>/=""7 9n this example, weGve created a chec+ constraint on the existing suppliers table called chec+HsupplierHname. 9t ensures that the supplierHname field only contains the following values: 9*M, Microsoft, or %(9693.

Drop a ChecN Constraint


The syntax for dropping a chec+ constraint is: /LTE( T/'LE ta!le-na%e *rop CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$ppliers *rop CO#ST(/>#T checN-s$pplier-i*7 9n this example, weGre dropping a chec+ constraint on the suppliers table called chec+HsupplierHid.

Ena!le a ChecN Constraint


The syntax for enabling a chec+ constraint is: /LTE( T/'LE ta!le-na%e ena!le CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$ppliers ena!le CO#ST(/>#T checN-s$pplier-i*7 9n this example, weGre enabling a chec+ constraint on the suppliers table called chec+HsupplierHid.

Disa!le a ChecN Constraint


The syntax for disabling a chec+ constraint is: /LTE( T/'LE ta!le-na%e *isa!le CO#ST(/>#T constraint-na%e7

4or exa%ple: /LTE( T/'LE s$ppliers *isa!le CO#ST(/>#T checN-s$pplier-i*7 9n this example, weGre disabling a chec+ constraint on the suppliers table called chec+HsupplierHid.

Oracle/PLSQL: >n*exes
Chat is an >n*exW
3n in*ex is a performance#tuning method of allowing faster retrieval of records. 3n index creates an entry for each value that appears in the indexed columns. *y default, Oracle creates *#tree indexes.

Create an >n*ex
The syntax for creating a index is: C(E/TE .1#>Q1E0 >#DEO in*ex-na%e O# ta!le-na%e (col$%n19 col$%n59 < col$%n-n" . COKP1TE ST/T>ST>CS 07 >%9D>B indicates that the combination of values in the indexed columns must be uniIue. 5OM->TB $T3T9$T95$ tells Oracle to collect statistics during the creation of the index. The statistics are then used by the optimizer to choose a Eplan of executionE when $D& statements are executed.

4or exa%ple: C(E/TE >#DEO s$pplier-i*x O# s$pplier (s$pplier-na%e"7 9n this example, weGve created an index on the supplier table called supplierHidx. 9t consists of only one field # the supplierHname field.

!e could also create an index with more than one field as in the example below: C(E/TE >#DEO s$pplier-i*x O# s$pplier (s$pplier-na%e9 city"7

!e could also choose to collect statistics upon creation of the index as follows: C(E/TE >#DEO s$pplier-i*x O# s$pplier (s$pplier-na%e9 city" COKP1TE ST/T>ST>CS7

Create a 4$nction@'ase* >n*ex


9n Oracle, you are not restricted to creating indexes on only columns. Fou can create function#based indexes. The syntax for creating a function#based index is: C(E/TE .1#>Q1E0 >#DEO in*ex-na%e O# ta!le-na%e ( $nction19 $nction59 < $nction-n" . COKP1TE ST/T>ST>CS 07

4or exa%ple: C(E/TE >#DEO s$pplier-i*x O# s$pplier (1PPE((s$pplier-na%e""7 9n this example, weGve created an index based on the uppercase evaluation of the supplier_name field.

=owever, to be sure that the Oracle optimizer uses this index when executing your $D& statements, be sure that >--BA(supplierHname) does not evaluate to a %>&& value. To ensure this, add 1PPE((s$pplier-na%e" >S #OT #1LL to your !=BAB clause as follows: SELECT s$pplier-i*9 s$pplier-na%e9 1PPE((s$pplier-na%e" 4(OK s$pplier CAE(E 1PPE((s$pplier-na%e" >S #OT #1LL O(DE( 'L 1PPE((s$pplier-na%e"7

(ena%e an >n*ex
The syntax for renaming an index is: /LTE( >#DEO in*ex-na%e (E#/KE TO ne)-in*ex-na%e7

4or exa%ple: /LTE( >#DEO s$pplier-i*x (E#/KE TO s$pplier-in*ex-na%e7 9n this example, weGre renaming the index called supplier_idx to supplier_index_name.

Collect Statistics on an >n*ex


9f you forgot to collect statistics on the index when you first created it or you want to update the statistics, you can always use the 3&TBA 9%6BK command to collect statistics at a later date. The syntax for collecting statistics on an index is:

/LTE( >#DEO in*ex-na%e (E'1>LD COKP1TE ST/T>ST>CS7

4or exa%ple: /LTE( >#DEO s$pplier-i*x (E'1>LD COKP1TE ST/T>ST>CS7 9n this example, weGre collecting statistics for the index called supplierHidx.

Drop an >n*ex
The syntax for dropping an index is: D(OP >#DEO in*ex-na%e7

4or exa%ple: D(OP >#DEO s$pplier-i*x7 9n this example, weGre dropping an index called supplierHidx.

Oracle/PLSQL: Creating 4$nctions

9n Oracle, you can create your own functions. The syntax for a function is: C(E/TE .O( (EPL/CE0 41#CT>O# $nction-na%e . (para%eter .9para%eter0" 0 (ET1(# ret$rn-*atatype >S 3 /S .*eclaration-section0 'EB># exec$ta!le-section .EOCEPT>O# exception-section0 E#D . $nction-na%e07

!hen you create a procedure or function, you may define parameters. There are three types of parameters that can be declared: .. 2. /. ># # The parameter can be referenced by the procedure or function. The value of the parameter can not be overwritten by the procedure or function. O1T # The parameter can not be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function. ># O1T # The parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function.

The following is a simple example of a function: C(E/TE O( (EPL/CE 4$nction 4in*Co$rse ( na%e-in ># ,archar5 " (ET1(# n$%!er >S cn$%!er n$%!er7 c$rsor c1 is select co$rse-n$%!er

ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB># open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 close c17 (ET1(# cn$%!er7 EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 E#D7 This function is called "ind5ourse. 9t has one parameter called name_in and it returns a number. The function will return the course number if it finds a match based on course name. Otherwise, it returns a 77777.

Fou could then reference your new function in an $D& statement as follows: select co$rse-na%e9 4in*Co$rse(co$rse-na%e" as co$rse-i* ro% co$rses )here s$!&ect 2 =Kathe%atics=7

Oracle/PLSQL: Creating Proce*$res


9n Oracle, you can create your own procedures.

The syntax for a procedure is: C(E/TE .O( (EPL/CE0 P(OCED1(E proce*$re-na%e . (para%eter .9para%eter0" 0 >S .*eclaration-section0 'EB># exec$ta!le-section .EOCEPT>O# exception-section0 E#D .proce*$re-na%e07

!hen you create a procedure or function, you may define parameters. There are three types of parameters that can be declared: .. 2. /. ># # The parameter can be referenced by the procedure or function. The value of the parameter can not be overwritten by the procedure or function. O1T # The parameter can not be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function. ># O1T # The parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function.

The following is a simple example of a procedure: C(E/TE O( (EPL/CE Proce*$re 1p*ateCo$rse ( na%e-in ># ,archar5 " >S cn$%!er n$%!er7 c$rsor c1 is select co$rse-n$%!er ro% co$rses-t!l )here co$rse-na%e 2 na%e-in7 'EB>#

open c17 etch c1 into cn$%!er7 i c1Snot o$n* then cn$%!er :2 99997 en* i 7 insert into st$*ent-co$rses ( co$rse-na%e9 co$rse-n$%!er" ,al$es ( na%e-in9 cn$%!er "7 co%%it7 close c17 EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 E#D7 This procedure is called >pdate5ourse. 9t has one parameter called name_in. The procedure will loo+up the courseHnumber based on course name. 9f it does not find a match, it defaults the course number to 77777. 9t then inserts a new record into the studentHcourses table.

Oracle/PLSQL Topics: Creating Triggers


9nsert Triggers: 'E4O(E >#SE(T Trigger /4TE( >#SE(T Trigger >pdate Triggers:

'E4O(E 1PD/TE Trigger /4TE( 1PD/TE Trigger 6elete Triggers: 'E4O(E DELETE Trigger /4TE( DELETE Trigger 6rop Triggers: Drop a Trigger 6isableOBnable Triggers: Disa!le a Trigger Disa!le all Triggers on a ta!le Ena!le a Trigger Ena!le all Triggers on a ta!le

Oracle/PLSQL: 'E4O(E >#SE(T Trigger


3 *B"OAB 9%$BAT Trigger means that Oracle will fire this trigger before the 9%$BAT operation is executed. The syntax for an *B"OAB 9%$BAT Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name 'E4O(E >#SE(T O# table_name

. 4O( E/CA (OC 0 DECL/(E @@ ,aria!le *eclarations 'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create a *B"OAB trigger on a view. Fou can update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* M$antity cost-per-ite% total-cost create-*ate create*-!y "7

n$%!er(J"9 n$%!er(6"9 n$%!er(;95"9 n$%!er(895"9 *ate9 ,archar5(10"

!e could then create a *B"OAB 9%$BAT trigger as follows:

C(E/TE O( (EPL/CE T(>BBE( or*ers-!e ore-insert 'E4O(E >#SE(T O# or*ers 4O( E/CA (OC DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing >#SE(T into ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ 1p*ate create-*ate iel* to c$rrent syste% *ate :ne)<create-*ate :2 sys*ate7 @@ 1p*ate create*-!y iel* to the $serna%e o the person per or%ing the >#SE(T :ne)<create*-!y :2 ,-$serna%e7 E#D7

Oracle/PLSQL: /4TE( >#SE(T Trigger


3n 3"TBA 9%$BAT Trigger means that Oracle will fire this trigger after the 9%$BAT operation is executed. The syntax for an 3"TBA 9%$BAT Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name /4TE( >#SE(T O# table_name . 4O( E/CA (OC 0 DECL/(E @@ ,aria!le *eclarations

'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create an 3"TBA trigger on a view. Fou can not update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* n$%!er(J"9 M$antity n$%!er(6"9 cost-per-ite% n$%!er(;95"9 total-cost n$%!er(895" "7

!e could then create an 3"TBA 9%$BAT trigger as follows: C(E/TE O( (EPL/CE T(>BBE( or*ers-a ter-insert /4TE( >#SE(T O# or*ers 4O( E/CA (OC

DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing the >#SE(T into the ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ >nsert recor* into a$*it ta!le >#SE(T >#TO or*ers-a$*it ( or*er-i*9 M$antity9 cost-per-ite%9 total-cost9 $serna%e " +/L1ES ( :ne)<or*er-i*9 :ne)<M$antity9 :ne)<cost-per-ite%9 :ne)<total-cost9 ,-$serna%e "7 E#D7

Oracle/PLSQL: 'E4O(E 1PD/TE Trigger


3 *B"OAB >-63TB Trigger means that Oracle will fire this trigger before the >-63TB operation is executed. The syntax for an *B"OAB >-63TB Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name 'E4O(E 1PD/TE O# table_name . 4O( E/CA (OC 0 DECL/(E

@@ ,aria!le *eclarations 'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create a *B"OAB trigger on a view. Fou can update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* M$antity cost-per-ite% total-cost $p*ate*-*ate $p*ate*-!y "7

n$%!er(J"9 n$%!er(6"9 n$%!er(;95"9 n$%!er(895"9 *ate9 ,archar5(10"

!e could then create a *B"OAB >-63TB trigger as follows:

C(E/TE O( (EPL/CE T(>BBE( or*ers-!e ore-$p*ate 'E4O(E 1PD/TE O# or*ers 4O( E/CA (OC DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing 1PD/TE on the ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ 1p*ate $p*ate*-*ate iel* to c$rrent syste% *ate :ne)<$p*ate*-*ate :2 sys*ate7 @@ 1p*ate $p*ate*-!y iel* to the $serna%e o the person per or%ing the 1PD/TE :ne)<$p*ate*-!y :2 ,-$serna%e7 E#D7

Oracle/PLSQL: /4TE( 1PD/TE Trigger


3n 3"TBA >-63TB Trigger means that Oracle will fire this trigger after the >-63TB operation is executed. The syntax for an 3"TBA >-63TB Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name /4TE( 1PD/TE O# table_name . 4O( E/CA (OC 0 DECL/(E @@ ,aria!le *eclarations

'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create an 3"TBA trigger on a view. Fou can not update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* M$antity cost-per-ite% total-cost "7

n$%!er(J"9 n$%!er(6"9 n$%!er(;95"9 n$%!er(895"

!e could then create an 3"TBA >-63TB trigger as follows: C(E/TE O( (EPL/CE T(>BBE( or*ers-a ter-$p*ate /4TE( 1PD/TE O# or*ers 4O( E/CA (OC

DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing 1PD/TE into ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ >nsert recor* into a$*it ta!le >#SE(T >#TO or*ers-a$*it ( or*er-i*9 M$antity-!e ore9 M$antity-a ter9 $serna%e " +/L1ES ( :ne)<or*er-i*9 :ol*<M$antity9 :ne)<M$antity9 ,-$serna%e "7 E#D7

Oracle/PLSQL: 'E4O(E DELETE Trigger


3 *B"OAB 6B&BTB Trigger means that Oracle will fire this trigger before the 6B&BTB operation is executed. The syntax for an *B"OAB 6B&BTB Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name 'E4O(E DELETE O# table_name . 4O( E/CA (OC 0 DECL/(E @@ ,aria!le *eclarations

'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create a *B"OAB trigger on a view. Fou can update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* M$antity cost-per-ite% total-cost "7

n$%!er(J"9 n$%!er(6"9 n$%!er(;95"9 n$%!er(895"

!e could then create a *B"OAB 6B&BTB trigger as follows: C(E/TE O( (EPL/CE T(>BBE( or*ers-!e ore-*elete 'E4O(E DELETE O# or*ers 4O( E/CA (OC

DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing the DELETE on the ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ >nsert recor* into a$*it ta!le >#SE(T >#TO or*ers-a$*it ( or*er-i*9 M$antity9 cost-per-ite%9 total-cost9 *elete-*ate9 *elete*-!y " +/L1ES ( :ol*<or*er-i*9 :ol*<M$antity9 :ol*<cost-per-ite%9 :ol*<total-cost9 sys*ate9 ,-$serna%e "7 E#D7

Oracle/PLSQL: /4TE( DELETE Trigger


3n 3"TBA 6B&BTB Trigger means that Oracle will fire this trigger after the 6B&BTB operation is executed. The syntax for an 3"TBA 6B&BTB Trigger is: C(E/TE or (EPL/CE T(>BBE( trigger_name /4TE( DELETE

O# table_name . 4O( E/CA (OC 0 DECL/(E @@ ,aria!le *eclarations 'EB># @@ trigger co*e EOCEPT>O# CAE# <<< @@ exception han*ling E#D7 tri..er_name is the name of the trigger to create. (estrictions:

Fou can not create an 3"TBA trigger on a view. Fou can not update the :%B! values. Fou can not update the :O&6 values.

4or exa%ple: 9f you had a table created as follows: C(E/TE T/'LE or*ers ( or*er-i* M$antity cost-per-ite% total-cost "7

n$%!er(J"9 n$%!er(6"9 n$%!er(;95"9 n$%!er(895"

!e could then create an 6B&BTB >-63TB trigger as follows:

C(E/TE O( (EPL/CE T(>BBE( or*ers-a ter-*elete /4TE( DELETE O# or*ers 4O( E/CA (OC DECL/(E ,-$serna%e ,archar5(10"7 'EB># @@ 4in* $serna%e o person per or%ing the DELETE on the ta!le SELECT $ser >#TO ,-$serna%e 4(OK *$al7 @@ >nsert recor* into a$*it ta!le >#SE(T >#TO or*ers-a$*it ( or*er-i*9 M$antity9 cost-per-ite%9 total-cost9 *elete-*ate9 *elete*-!y" +/L1ES ( :ol*<or*er-i*9 :ol*<M$antity9 :ol*<cost-per-ite%9 :ol*<total-cost9 sys*ate9 ,-$serna%e "7 E#D7

Oracle/PLSQL: Drop a Trigger


The syntax for a dropping a Trigger is:

D(OP T(>BBE( trigger_name7

4or exa%ple: 9f you had a trigger called ordersHbeforeHinsert, you could drop it with the following command: D(OP T(>BBE( or*ers-!e ore-insert7

Oracle/PLSQL: Disa!le a Trigger


The syntax for a disabling a Trigger is: /LTE( T(>BBE( trigger_name D>S/'LE7

4or exa%ple: 9f you had a trigger called ordersHbeforeHinsert, you could disable it with the following command: /LTE( T(>BBE( or*ers-!e ore-insert D>S/'LE7

Oracle/PLSQL: Disa!le all Triggers on a ta!le


The syntax for a disabling all Triggers on a table is: /LTE( T/'LE table_name D>S/'LE /LL T(>BBE(S7

4or exa%ple: 9f you had a table called orders and you wanted to disable all triggers on this table, you could execute the following command: /LTE( T/'LE or*ers D>S/'LE /LL T(>BBE(S7

Oracle/PLSQL: Ena!le a Trigger


The syntax for a enabling a Trigger is: /LTE( T(>BBE( trigger_name E#/'LE7

4or exa%ple: 9f you had a trigger called ordersHbeforeHinsert, you could enable it with the following command: /LTE( T(>BBE( or*ers-!e ore-insert E#/'LE7

Oracle/PLSQL: Ena!le all Triggers on a ta!le


The syntax for a enabling all Triggers on a table is: /LTE( T/'LE table_name E#/'LE /LL T(>BBE(S7

4or exa%ple: 9f you had a table called orders and you wanted to enable all triggers on this table, you could execute the following command:

/LTE( T/'LE or*ers E#/'LE /LL T(>BBE(S7

Oracle/PLSQL Topics: Exception Aan*ling


!eGve categorized exception handling into the following topics: #a%e* Syste% Exceptions #a%e* Progra%%er@De ine* Exceptions CAE# OTAE(S Cla$se

SQLCODE 4$nction SQLE((K 4$nction

Oracle Error Kessages

Oracle/PLSQL: #a%e* Syste% Exceptions

What is a named system exception?


%amed system exceptions are exceptions that have been given names by -&O$D&. They are named in the $T3%63A6 pac+age in -&O$D& and do not need to be defined by the programmer. Oracle has a standard set of exceptions already named as follows:

Oracle Exception #a%e 6>-H(3&HO%H9%6BK

Oracle Error OA3# .

Explanation Fou tried to execute an 9%$BAT or >-63TB statement that has created a duplicate value in a field restricted by a uniIue index. Fou were waiting for a resource and you timed out. The remote portion of a transaction has rolled bac+. Fou tried to reference a cursor that does not yet exist. This may have happened because youGve executed a "BT5= cursor or 5&O$B cursor before O-B%ing the cursor. Fou tried to execute a call to Oracle before logging in. Fou tried to log into Oracle with an invalid usernameOpassword combination. Fou tried one of the following: .. Fou executed a $B&B5T 9%TO statement and no rows were returned. 2. Fou referenced an uninitialized row in a table. /. Fou read past the end of file with the >T&H"9&B pac+age.

T9MBO>THO%HAB$O>A5B

OA3#

2. 8. .

TA3%$35T9O%H*35?B6HO>T OA3# 9%(3&96H5>A$OA OA3# .

%OTH&O))B6HO% &O)9%H6B%9B6 %OH63T3H"O>%6

OA3# . .2 OA3# . .1 OA3# .' /

TOOHM3%FHAO!$

OA3# .'22

Fou tried to execute a $B&B5T 9%TO

statement and more than one row was returned. PBAOH69(96B 9%(3&96H%>M*BA OA3# .'18 OA3# .122 Fou tried to divide a number by zero. Fou tried to execute an $D& statement that tried to convert a string to a number, but it was unsuccessful. Fou ran out of memory or memory was corrupted. This is a generic E5ontact Oracle supportE message because an internal problem was encountered. Fou tried to perform an operation and there was a error on a conversion, truncation, or invalid constraining of numeric or character data. Fou tried to open a cursor that is already open.

$TOA3)BHBAAOA -AO)A3MHBAAOA

OA3# 82 OA3# 82 .

(3&>BHBAAOA

OA3# 82 2

5>A$OAH3&AB36FHO-B%

OA3# 82..

The syntax for the %amed $ystem Bxception in a procedure is: C(E/TE .O( (EPL/CE0 P(OCED1(E proce*$re-na%e . (para%eter .9para%eter0" 0 >S .*eclaration-section0 'EB># exec$ta!le-section EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0

CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D .proce*$re-na%e07

The syntax for the %amed $ystem Bxception in a function is: C(E/TE .O( (EPL/CE0 41#CT>O# $nction-na%e . (para%eter .9para%eter0" 0 (ET1(# ret$rn-*atatype >S 3 /S .*eclaration-section0 'EB># exec$ta!le-section EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0 CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0

E#D . $nction-na%e07

=ere is an example of a procedure that uses a %amed $ystem Bxception: C(E/TE O( (EPL/CE P(OCED1(E a**-ne)-s$pplier (s$pplier-i*-in ># #1K'E(9 s$pplier-na%e-in ># +/(CA/(5" >S 'EB># >#SE(T >#TO s$ppliers (s$pplier-i*9 s$pplier-na%e " +/L1ES ( s$pplier-i*-in9 s$pplier-na%e-in "7 EOCEPT>O# CAE# D1P-+/L-O#->#DEO TAE# raise-application-error (@500019=Lo$ ha,e trie* to insert a *$plicate s$pplier-i*<="7 CAE# OTAE(S TAE# raise-application-error (@500059=/n error has occ$rre* inserting a s$pplier<="7 E#D7 9n this example, we are trapping the %amed $ystem Bxception called D1P-+/L-O#->#DEO. !e are also using the CAE# OTAE(S cla$se to trap all remaining exceptions.

Oracle/PLSQL: #a%e* Progra%%er@De ine* Exceptions

What is a named programmer-defined exception?


$ometimes, it is necessary for programmers to name and trap their own exceptions # ones that arenGt defined already by -&O$D&. These are called %amed -rogrammer# 6efined Bxceptions. The syntax for the %amed -rogrammer#6efined Bxception in a procedure is:

C(E/TE .O( (EPL/CE0 P(OCED1(E proce*$re-na%e . (para%eter .9para%eter0" 0 >S .*eclaration-section0 exception-na%e EOCEPT>O#7 'EB># exec$ta!le-section (/>SE exception-na%e 7 EOCEPT>O# CAE# exception-na%e TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D .proce*$re-na%e07

The syntax for the %amed -rogrammer#6efined Bxception in a function is: C(E/TE .O( (EPL/CE0 41#CT>O# $nction-na%e . (para%eter .9para%eter0" 0 (ET1(# ret$rn-*atatype >S 3 /S .*eclaration-section0 exception-na%e EOCEPT>O#7 'EB># exec$ta!le-section

(/>SE exception-na%e 7 EOCEPT>O# CAE# exception-na%e TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D . $nction-na%e07

=ere is an example of a procedure that uses a %amed -rogrammer#6efined Bxception: C(E/TE O( (EPL/CE P(OCED1(E a**-ne)-or*er (or*er-i*-in ># #1K'E(9 sales-in ># #1K'E(" >S no-sales EOCEPT>O#7 'EB># >4 sales-in 2 0 TAE# (/>SE no-sales7 ELSE >#SE(T >#TO or*ers (or*er-i*9 total-sales " +/L1ES ( or*er-i*-in9 sales-in "7 E#D >47 EOCEPT>O# CAE# no-sales TAE# raise-application-error (@500019=Lo$ %$st ha,e sales in or*er to s$!%it the or*er<="7 CAE# OTAE(S TAE# raise-application-error (@500059=/n error has occ$rre* inserting an or*er<="7

E#D7 9n this example, we have declared a %amed -rogrammer#6efined Bxception called no-sales in our declaration statement with the following code: no-sales EOCEPT>O#7

!eGve then raised the exception in the executable section of the code: >4 sales-in 2 0 TAE# (/>SE no-sales7 %ow if the sales_in variable contains a zero, our code will @ump directly to the %amed -rogrammer#6efined Bxception called no-sales.

"inally, we tell our procedure what to do when the no-sales exception is encountered by including code in the !=B% clause: CAE# no-sales TAE# raise-application-error (@500019=Lo$ %$st ha,e sales in or*er to s$!%it the or*er<="7

!e are also using the CAE# OTAE(S cla$se to trap all remaining exceptions: CAE# OTAE(S TAE# raise-application-error (@500059=/n error has occ$rre* inserting an or*er<="7

Oracle/PLSQL: CAE# OTAE(S Cla$se

What is a WHEN OTHERS clause?

The !=B% OT=BA$ clause is used to trap all remaining exceptions that have not been handled by your #a%e* Syste% Exceptions and #a%e* Progra%%er@De ine* Exceptions. The syntax for the !=B% OT=BA$ clause in a procedure is: C(E/TE .O( (EPL/CE0 P(OCED1(E proce*$re-na%e . (para%eter .9para%eter0" 0 >S .*eclaration-section0 'EB># exec$ta!le-section EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0 CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D .proce*$re-na%e07

The syntax for the !=B% OT=BA$ clause in a function is: C(E/TE .O( (EPL/CE0 41#CT>O# $nction-na%e . (para%eter .9para%eter0" 0 (ET1(# ret$rn-*atatype >S 3 /S .*eclaration-section0

'EB># exec$ta!le-section EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0 CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D . $nction-na%e07

=ere is an example of a procedure that uses a !=B% OT=BA$ clause: C(E/TE O( (EPL/CE P(OCED1(E a**-ne)-or*er (or*er-i*-in ># #1K'E(9 sales-in ># #1K'E(" >S no-sales EOCEPT>O#7 'EB># >4 sales-in 2 0 TAE# (/>SE no-sales7 ELSE >#SE(T >#TO or*ers (or*er-i*9 total-sales " +/L1ES ( or*er-i*-in9 sales-in "7 E#D >47

EOCEPT>O# CAE# D1P-+/L-O#->#DEO TAE# raise-application-error (@500019=Lo$ ha,e trie* to insert a *$plicate or*er-i*<="7 CAE# no-sales TAE# raise-application-error (@500019=Lo$ %$st ha,e sales in or*er to s$!%it the or*er<="7 CAE# OTAE(S TAE# raise-application-error (@500059=/n error has occ$rre* inserting an or*er<="7 E#D7 9n this example, if an exception is encountered that is not a D1P-+/L-O#->#DEO or a no-sales, it will be trapped by the !=B% OT=BA$ clause.

Fre uently !s"ed #uestions

Q$estion: 9s there any way to get the OA3 error number (andOor description) for the errors that will fall into OT=BA$J $omething li+e: !=B% OT=BA$ T=B% GBrror number G Q Brr.%umberQ G has happen.G /ns)er: Fes, you can use SQLCODE $nction to retrieve the error number and SQLE((K $nction to retrieve the error message. "or example, you could raise the error as follows: EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 E#D7

Or you could log the error to a table as follows: EOCEPT>O# CAE# OTAE(S TAE# err-co*e :2 SQLCODE7 err-%sg :2 s$!str(SQLE((K9 19 500"7 >#SE(T >#TO a$*it-ta!le (error-n$%!er9 error-%essage" +/L1ES (err-co*e9 err-%sg"7 E#D7

Oracle/PLSQL: SQLCODE 4$nction

What does the S#$%O&E Function do?


The $D&5O6B function returns the error number associated with the most recently raised error exception. This function should only be used within the Bxception =andling section of your code: EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0 CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D .proce*$re-na%e07

Fou could use the $D&5O6B function to raise an error as follows: EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 E#D7

Or you could log the error to a table as follows: EOCEPT>O# CAE# OTAE(S TAE# err-co*e :2 SQLCODE7 err-%sg :2 s$!str(SQLE((K9 19 500"7 >#SE(T >#TO a$*it-ta!le (error-n$%!er9 error-%essage" +/L1ES (err-co*e9 err-%sg"7 E#D7

&earn more about the SQLE((K 4$nction.

Oracle/PLSQL: SQLE((K 4$nction

What does the S#$ERR' Function do?


The $D&BAAM function returns the error message associated with the most recently raised error exception. This function should only be used within the Bxception =andling section of your code:

EOCEPT>O# CAE# exception-na%e1 TAE# .state%ents0 CAE# exception-na%e5 TAE# .state%ents0 CAE# exception-na%e-n TAE# .state%ents0 CAE# OTAE(S TAE# .state%ents0 E#D .proce*$re-na%e07

Fou could use the $D&BAAM function to raise an error as follows: EOCEPT>O# CAE# OTAE(S TAE# raise-application-error(@500019=/n error )as enco$ntere* @ =33SQLCODE33= @E((O(@ =33SQLE((K"7 E#D7

Or you could log the error to a table as follows: EOCEPT>O# CAE# OTAE(S TAE# err-co*e :2 SQLCODE7 err-%sg :2 s$!str(SQLE((K9 19 500"7 >#SE(T >#TO a$*it-ta!le (error-n$%!er9 error-%essage" +/L1ES (err-co*e9 err-%sg"7 E#D7

&earn more about the SQLCODE 4$nction.

Oracle/PLSQL Topics: Oracle Error Kessages


The following is a listing of Oracle Brror Messages: .# 077 O(/@000J1 O(/@000J6 O(/@000JI O(/@000J8 O(/@000;0 O(/@000;: O(/@000;8 O(/@000I1 O(/@000I8 O(/@00100 O(/@0010I O(/@00501 O(/@005JI O(/@00:01 O(/@00:06 O(/@00:;1 O(/@00601

O(/@00001 O(/@00018 O(/@00050 O(/@0005: O(/@00058 O(/@000:6

777 O(/@0091I O(/@00918 O(/@00919 O(/@00950 O(/@0095: O(/@00956 O(/@0095J O(/@0095; O(/@0095I O(/@00958 O(/@009:1 O(/@009:5 O(/@009:: O(/@009:6 O(/@009:J O(/@009:; O(/@009:I O(/@009:8 O(/@009:9 O(/@00965 O(/@0096; O(/@0096I O(/@00968 O(/@009JJ O(/@009JI O(/@009;0 O(/@009;5 O(/@009I1 O(/@009I5 O(/@009IJ O(/@009I9 O(/@00980 O(/@00986 O(/@0098J O(/@0099J

O(/@00900 O(/@00905 O(/@0090: O(/@00906 O(/@0090J O(/@0090; O(/@0090I O(/@00908 O(/@00909 O(/@00910 O(/@00911 O(/@0091:

# ./77

O(/@01000 O(/@01001 O(/@01005 O(/@01006 O(/@0100J O(/@0100; O(/@0100I O(/@01008 O(/@01015

O(/@0101: O(/@01016 O(/@0101I O(/@0105: O(/@010:1 O(/@010:: O(/@010:6 O(/@010:J O(/@010:I

O(/@010:9 O(/@01060 O(/@01065 O(/@0106J O(/@010J5 O(/@010I6 O(/@01089 O(/@01109 O(/@0111:

O(/@01116 O(/@011:: O(/@01500 O(/@015:6

.'

# .'77 O(/@01655 O(/@0165: O(/@01656 O(/@0165J O(/@0165; O(/@0165I O(/@01658 O(/@01659 O(/@016:0 O(/@016:5 O(/@016:: O(/@016:6 O(/@016:J O(/@016:; O(/@016:I O(/@016:8 O(/@016:9 O(/@01660 O(/@01661 O(/@01665 O(/@0166; O(/@01668 O(/@01669 O(/@016J1 O(/@016J5 O(/@016J: O(/@016J6 O(/@016;1 O(/@016;J O(/@016;8 O(/@016I1 O(/@016I;

O(/@01600 O(/@01601 O(/@01605 O(/@0160: O(/@01606 O(/@0160J O(/@0160; O(/@0160I O(/@01608 O(/@0161; O(/@0161I O(/@01618

.2

# .777 O(/@01I19 O(/@01I55 O(/@01I5: O(/@01I56 O(/@01I5I O(/@01I58 O(/@01I6I O(/@01IJ; O(/@01IIJ O(/@01I8J O(/@01I89 O(/@01I90 O(/@01810 O(/@01818 O(/@01850 O(/@01851 O(/@018:0 O(/@018:9 O(/@0186; O(/@0186I O(/@018J8 O(/@018;1 O(/@0191; O(/@01918 O(/@019J0

O(/@01J06 O(/@01J0; O(/@01JJJ O(/@01;:5 O(/@01;J5 O(/@01;J: O(/@01I00 O(/@01I06 O(/@01I10

O(/@01I11

O(/@01II9

O(/@0186:

# 8'77 O(/@055;8 O(/@055I0 O(/@05590 O(/@05591 O(/@05595 O(/@0559: O(/@05598 O(/@056:I O(/@05666 O(/@05669 O(/@0:11: O(/@06000 O(/@060:1 O(/@06088 O(/@06091 O(/@06095 O(/@06098

O(/@0500: O(/@05011 O(/@05056 O(/@050;9 O(/@0508; O(/@055J; O(/@055;0

82

# 7777 O(/@0;J08 O(/@0;J10 O(/@0;J11 O(/@0;J15 O(/@0;J16 O(/@0;J1J O(/@0;JJ0 O(/@0;J;6 O(/@0;JI5 O(/@0;JIJ O(/@08005 O(/@0810:

O(/@0;J00 O(/@0;J01 O(/@0;J05 O(/@0;J0:

# .2777 O(/@151J6

Oracle/PLSQL: Brant/(e,oNe Pri,ileges

(rant )ri*ileges on Ta+les


Fou can grant users various privileges to tables. These privileges can be any combination of select, insert, update, delete, references, alter, and index. *elow is an explanation of what each privilege means.

Pri,ilege $elect 9nsert >pdate 6elete Aeferences 3lter 9ndex

Description 3bility to Iuery the table with a select statement. 3bility to add new rows to the table with the insert statement. 3bility to update rows in the table with the update statement. 3bility to delete rows from the table with the delete statement. 3bility to create a constraint that refers to the table. 3bility to change the table definition with the alter table statement. 3bility to create an index on the table with the create index statement.

The syntax for granting privileges on a table is: grant pri,ileges on o!&ect to $ser7 "or example, if you wanted to grant select, insert, update, and delete privileges on a table called suppliers to a user name smith@, you would execute the following statement: grant select9 insert9 $p*ate9 *elete on s$ppliers to s%ith&7 Fou can also use the all +eyword to indicate that you wish all permissions to be granted. "or example: grant all on s$ppliers to s%ith&7 9f you wanted to grant select access on your table to all users, you could grant the privileges to the public +eyword. "or example: grant select on s$ppliers to p$!lic7

Re*o"e )ri*ileges on Ta+les


Once you have granted privileges, you may need to revo+e some or all of these privileges. To do this, you can execute a revo+e command. Fou can revo+e any combination of select, insert, update, delete, references, alter, and index. The syntax for revo+ing privileges on a table is: re,oNe pri,ileges on o!&ect ro% $ser7 "or example, if you wanted to revo+e delete privileges on a table called suppliers from a user named anderson, you would execute the following statement: re,oNe *elete on s$ppliers ro% an*erson7 9f you wanted to revo+e all privileges on a table, you could use the all +eyword. "or example: re,oNe all on s$ppliers ro% an*erson7 9f you had granted privileges to public (all users) and you wanted to revo+e these privileges, you could execute the following statement: re,oNe all on s$ppliers ro% p$!lic7

(rant )ri*ileges on Functions,)rocedures


!hen dealing with functions and procedures, you can grant users the ability to execute these functions and procedures. The Bxecute privilege is explained below: Pri,ilege Bxecute Description 3bility to compile the functionOprocedure. 3bility to execute the functionOprocedure directly.

The syntax for granting execute privileges on a functionOprocedure is: grant exec$te on o!&ect to $ser7 "or example, if you had a function called "indH(alue and you wanted to grant execute access to the user named smith@, you would execute the following statement: grant exec$te on 4in*-+al$e to s%ith&7 9f you wanted to grant all users the ability to execute this function, you would execute the following: grant exec$te on 4in*-+al$e to p$!lic7

Re*o"e )ri*ileges on Functions,)rocedures


Once you have granted execute privileges on a function or procedure, you may need to revo+e these privileges from a user. To do this, you can execute a revo+e command. The syntax for the revo+ing privileges on a function or procedure is: re,oNe exec$te on o!&ect ro% $ser7 9f you wanted to revo+e execute privileges on a function called "indH(alue from a user named anderson, you would execute the following statement: re,oNe exec$te on 4in*-+al$e ro% an*erson7 9f you had granted privileges to public (all users) and you wanted to revo+e these privileges, you could execute the following statement: re,oNe exec$te on 4in*-+al$e ro% p$!lic7

Oracle/PLSQL: (oles

3 role is a set or group of privileges that can be granted to users or another role. This is a great way for database administrators to save time and effort.

%reating a Role
To create a role, you must have 5AB3TB AO&B system privileges. The syntax for creating a role is: C(E/TE (OLE role-na%e . #OT >DE#T>4>ED 3 >DE#T>4>ED E'L pass)or* 3 1S>#B .sche%a<0 pacNage 3 EOTE(#/LLL 3 BLO'/LLL F 7 %ote: 9f both the #OT >DE#T>4>ED and >DE#T>4>ED phrases are omitted in the 5AB3TB AO&B statement, the role will be created as a %OT 96B%T9"9B6 role. The role-na%e phrase is the name of the new role that you are creating. This is how you will refer to the grouping of privileges. The #OT >DE#T>4>ED phrase means that the role is immediately enabled. %o password is reIuired to enable the role. The >DE#T>4>ED phrase means that a user must be authorized by a specified method before the role is enabled. The 'L pass)or* phrase means that a user must supply a password to enable the role. The 1S>#B pacNage phrase means that you are creating an application role # a role that is enabled only by applications using an authorized pac+age. The EOTE(#/LLL phrase means that a user must be authorized by an external service to enable the role. 3n external service can be an operating system or third#party service. The BLO'/LLL phrase means that a user must be authorized by the enterprise directory service to enable the role.

4or exa%ple:

C(E/TE (OLE test-role7 This first example creates a role called testHrole. C(E/TE (OLE test-role >DE#T>4>ED 'L test15:7 This second example creates the same role called testHrole, but now it is password protected with the password of test.2/.

(rant )ri*ileges -on Ta+les. to Roles


Fou can grant roles various privileges to tables. These privileges can be any combination of select, insert, update, delete, references, alter, and index. *elow is an explanation of what each privilege means. Pri,ilege $elect 9nsert >pdate 6elete Aeferences 3lter 9ndex Description 3bility to Iuery the table with a select statement. 3bility to add new rows to the table with the insert statement. 3bility to update rows in the table with the update statement. 3bility to delete rows from the table with the delete statement. 3bility to create a constraint that refers to the table. 3bility to change the table definition with the alter table statement. 3bility to create an index on the table with the create index statement.

The syntax for granting privileges on a table is: grant pri,ileges on o!&ect to role-na%e

"or example, if you wanted to grant select, insert, update, and delete privileges on a table called suppliers to a role named testHrole, you would execute the following statement: grant select9 insert9 $p*ate9 *elete on s$ppliers to test-role7 Fou can also use the all +eyword to indicate that you wish all permissions to be granted. "or example: grant all on s$ppliers to test-role7

Re*o"e )ri*ileges -on Ta+les. to Roles


Once you have granted privileges, you may need to revo+e some or all of these privileges. To do this, you can execute a revo+e command. Fou can revo+e any combination of select, insert, update, delete, references, alter, and index. The syntax for revo+ing privileges on a table is: re,oNe pri,ileges on o!&ect ro% role-na%e7 "or example, if you wanted to revo+e delete privileges on a table called suppliers from a role named testHrole, you would execute the following statement: re,oNe *elete on s$ppliers ro% test-role7 9f you wanted to revo+e all privileges on a table, you could use the all +eyword. "or example: re,oNe all on s$ppliers ro% test-role7

(rant )ri*ileges -on Functions,)rocedures. to Roles


!hen dealing with functions and procedures, you can grant roles the ability to execute these functions and procedures. The Bxecute privilege is explained below:

Pri,ilege Bxecute

Description 3bility to compile the functionOprocedure. 3bility to execute the functionOprocedure directly.

The syntax for granting execute privileges on a functionOprocedure is: grant exec$te on o!&ect to role-na%e7 "or example, if you had a function called "indH(alue and you wanted to grant execute access to the role named testHrole, you would execute the following statement: grant exec$te on 4in*-+al$e to test-role7

Re*o"e )ri*ileges -on Functions,)rocedures. to Roles


Once you have granted execute privileges on a function or procedure, you may need to revo+e these privileges from a role. To do this, you can execute a revo+e command. The syntax for the revo+ing privileges on a function or procedure is: re,oNe exec$te on o!&ect ro% role-na%e7 9f you wanted to revo+e execute privileges on a function called "indH(alue from a role named testHrole, you would execute the following statement: re,oNe exec$te on 4in*-+al$e ro% test-role7

(ranting the Role to a /ser


%ow, that youGve created the role and assigned the privileges to the role, youGll need to grant the role to specific users.

The syntax to grant a role to a user is: B(/#T role-na%e TO $ser-na%e7 4or exa%ple: B(/#T test-role to s%ith&7 This example would grant the role called testHrole to the user named smith@.

The SET RO$E statement


The $BT AO&B statement allows you to enable or disable a role for a current session. !hen a user logs into Oracle, all default roles are enabled, but non#default roles must be enabled with the $BT AO&B statement. The syntax for the $BT AO&B statement is: SET (OLE ( role-na%e . >DE#T>4>ED 'L pass)or* 0 3 /LL .EOCEPT role19 role59 <<< 0 3 #O#E "7 The role-na%e phrase is the name of the role that you wish to enable. The >DE#T>4>ED 'L pass)or* phrase is the password for the role to enable it. 9f the role does not have a password, this phrase can be omitted. The /LL phrase means that all roles should be enabled for this current session, except those listed in the EOCEPT phrase. The #O#E phrase disables all roles for the current session. (including all default roles)

4or exa%ple: SET (OLE test-role >DE#T>4>ED 'L test15:7 This example would enable the role called testHrole with a password of test.2/.

Setting a role as &EF!/$T Role


3 default role means that the role is always enabled for the current session at logon. 9t is not necessary to issue the $BT AO&B statement. To set a role as a 6B"3>&T role, you need to issue the 3&TBA >$BA statement. The syntax for setting a role as a 6B"3>&T role is: /LTE( 1SE( $ser-na%e DE4/1LT (OLE ( role-na%e 3 /LL .EOCEPT role19 role59 <<< 0 3 #O#E "7 The $ser-na%e phrase is the name of the user whose role you are setting as 6B"3>&T. The role-na%e phrase is the name of the role that you wish to set as 6B"3>&T. The /LL phrase means that all roles should be enabled as 6B"3>&T, except those listed in the EOCEPT phrase. The #O#E phrase disables all roles as 6B"3>&T.

4or exa%ple:

/LTE( 1SE( s%ith& DE4/1LT (OLE test-role7 This example would set the role called testHrole as a 6B"3>&T role for the user named smith@. /LTE( 1SE( s%ith& DE4/1LT (OLE /LL7 This example would set all roles assigned to smith@ as 6B"3>&T. /LTE( 1SE( s%ith& DE4/1LT (OLE /LL EOCEPT test-role7 This example would set all roles assigned to smith@ as 6B"3>&T, except for the role called testHrole.

&ropping a Role
9t is also possible to drop a role. The syntax for dropping a role is: D(OP (OLE role-na%e7

4or exa%ple: D(OP (OLE test-role7 This drop statement would drop the role called test_role that we defined earlier.

Oracle/PLSQL: Change a $ser=s pass)or* in Oracle


Q$estion: =ow do 9 change the password for a user in OracleJ

/ns)er: To change a userGs password in Oracle, you need to execute the alter user command. The syntax for changing a password is: alter $ser user_name i*enti ie* !y new_password7 user_name is the user whose password you wish to change. new_password is the new password to assign.

4or exa%ple: 9f you wanted to reset the password for a user named s%ith&, and you wanted to set the new password to a$t$%n, you would run the following command: alter $ser s%ith& i*enti ie* !y a$t$%n7

Oracle/PLSQL: Synony%s
3 synony% is an alternative name for ob@ects such as tables, views, seIuences, stored procedures, and other database ob@ects.

%reating or replacing a synonym


The syntax for creating a synonym is: create .or replace0 .p$!lic0 synony% .sche%a <0 synony%-na%e or .sche%a <0 o!&ect-na%e .X *!linN07 The or replace phrase allows you to recreate the synonym (if it already exists) without having to issue a 6AO- synonym command. The p$!lic phrase means that the synonym is a public synonym and is accessible to all users. Aemember though that the user must first have the appropriate privileges to the ob@ect to use the synonym. The sche%a phrase is the appropriate schema. 9f this phrase is omitted, Oracle assumes that you are referring to your own schema. The o!&ect-na%e phrase is the name of the ob@ect for which you are creating the synonym. 9t can be one of the following: table view seIuence stored procedure function pac+age materialized view @ava class schema ob@ect user#defined ob@ect synonym

4or exa%ple: create p$!lic synony% s$ppliers or app<s$ppliers7 This first example demonstrates how to create a synonym called suppliers. %ow, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. "or example: select ? ro% s$ppliers7

9f this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows: create or replace p$!lic synony% s$ppliers or app<s$ppliers7

&ropping a synonym
9t is also possible to drop a synonym. The syntax for dropping a synonym is: *rop .p$!lic0 synony% .sche%a <0 synony%-na%e . orce07 The p$!lic phrase allows you to drop a public synonym. 9f you have specified p$!lic, then you donGt specify a sche%a. The orce phrase will force Oracle to drop the synonym even if it has dependencies. 9t is probably not a good idea to use the orce phrase as it can cause invalidation of Oracle ob@ects.

4or exa%ple: *rop p$!lic synony% s$ppliers7 This drop statement would drop the synonym called suppliers that we defined earlier.

Oracle/PLSQL Topics: Q$estion U /ns)er


!eGve added this category to include some of our general Iuestions from viewers. &O%) 6ata Types:

Deter%ine the length o a LO#B iel* (etrie,e the ,al$e o a LO#B iel* $tring 6ata Types: Dealing )ith apostrophes/single M$otes in strings

Test a string or a n$%eric ,al$e Test a string or an alpha!etic ,al$e Test a string or an alphan$%eric ,al$e

Sort a ,archar5 iel* as a n$%eric iel* Extract arith%etic operators ro% a string Parse a string ,al$e an* then ret$rn a s$!string Di erence !et)een an e%pty string an* a n$ll ,al$e

Extract the *irectory path ro% a $ll ile path Extract the ilena%e (incl$*ing s$ ix" ro% a $ll ile path Extract the ilena%e s$ ix ro% a $ll ile path

63TB 6ata Types: >nsert a *ate/ti%e ,al$e into an Oracle ta!le (etrie,e the total elapse* ti%e in %in$tes !et)een t)o *ates 5ursors: C$rsor )ithin a c$rsor Proce*$re that o$tp$ts a *yna%ic PLSQL c$rsor C$rsor )ith ,aria!le in an T># CL/1SET Brrors: O(/@06098 Error /,oi* T*ata not o$n*T error in PLSQL co*e Aetrieve Top, Middle, or *ottom % records of a Iuery: (etrie,e Top # recor*s ro% a M$ery (etrie,e 'otto% # recor*s ro% a M$ery (etrie,e Ki**le # recor*s ro% a M$ery (etrie,e secon* highest ,al$e ro% a ta!le (etrie,e thir* highest ,al$e ro% a ta!le (etrie,e secon* lo)est ,al$e ro% a ta!le

(etrie,e thir* lo)est ,al$e ro% a ta!le $D&-lus: Exec$te an SQL script ile in SQLPl$s Pro%pt $ser or a para%eter ,al$e in SQLPl$s Miscellaneous: 4or%at a n$%!er in Oracle Calc$late the a,erage !et)een t)o *ates (et$rn error %essage )hen ret$rn *atatype is set to #1K'E( (oll!acN !eha,ior an* DDL=s Proce*$re to ret$rn a %onthly perio* Exec$te a $nction that is *e ine* in a pacNage /** *ays to a *ate (sNipping Sat$r*ays an* S$n*ays" (etrie,e Oracle ,ersion in or%ation (etrie,e the na%e o the Oracle instance c$rrently connecte* to (etrie,e pri%ary Ney in or%ation (etrie,e the ,al$e that occ$rs %ost in a col$%n B(O1P 'L Cla$se an* sorting

>nsert %$ltiple ro)s )ith a single >#SE(T state%ent

You might also like