Professional Documents
Culture Documents
5) what is sequence?
A sequence is a oracle object that is used to generate unique numbers.
A sequence is created using with CREATE SEQUENCE DDL command.
A sequence is accessed with SEQUENCE.NEXTVAL or SEQUENCE.CURRVAL
A CURRVAL can be accessed only after at least one NEXTVAL has been issued.
Once created can be used in any number of tables.
e.g
Declare
v_department classes.department%type
v_cursor classes.course%type
CURSOR c_classes IS
SELECT * FROM CLASSES where department = v_department and course = v_course
OPENING A CURSOR:
OPEN cursor_name
OPEN c_classes('HIS',101);
The following will raise an error because the select list does not match.
OPEN v_classesCV FOR Select department, course from classes.
PREDEFINED EXCEPTIONS:
Oracle has predefined several exceptions that corresponds to the most common oracle errors. The
identifiers for this exceptions are defined STANDARD package so it is not necessary to declare them in the
declarative section like user-defined.
It is possible to associate user-defined exception with oracle errors.
Some pre-defined exceptions.
DUP_VAL_ON_INDEX
INVALID_CURSOR
TRANSACTION_BACKED_OUT
NO_DATA_FOUND
TOO_MANY_ROWS
RAISING EXCEPTION:
When the error associated with an exception occurs the exception is raised.
The user-defined exceptions are raised explicitly via RAISE statement.
The Pre-defined exception(or user defined exception associated with an oracle error through
EXCRPTION_INIT pragma) are raised implicitly when their associated oracle error occurs.
If the oracle error that is not associated with an exception occurs this exception is caught by OTHERS
handler.
HANDLING EXCEPTION:
When exception is raised the control is passed to exception section of the block.
The exception section consists of handler for some or all exceptions.
An exception handler contains the code that is executed when the error associated with the exception
occurs.
EXCEPTION
WHEN exception_name THEN
Sequence of statement
WHEN exception_name THEN
Sequence of statement
WHEN OTHERS THEN
Sequence of statement
END;
EXCEPTION_INIT Pragma:
You can associate a named exception with a particular oracle error. This gives the ability to trap this error
specially rather than via an OTHER handler. This is done by EXCEPTION_INIT pragma.
PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number) ;
Declare
E_missingnull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_missingnull, -1400);
Begin
---
EXCPTION
When e_missingnull then
End;
RAISE_APPLICATION_ERROR:
You can use the built-in function RAISE_APPLICATION_ERROR to create your own error message it can
be more descriptive than named exceptions..
RAISE_APPLICATION_ERROR(error_numbr,error_message,[keep_message]);
By using this no special error handling is nessary for user-defined errors Vs pre-defined errors.
EXCEPTION PROPAGATION:
An exception can be occur in declarative, executable or exception section of a pl/sql block .
EXCEPTION RAISED IN THE EXECUTABLE SECTION:
1) If the current block has the handler for the exception, executes it and complete the block
successfully control will pass to enclosing block.
2) If there is no handler for the current exception, propagates the exception to by raising it in enclosig
block.
EXCEPTION RAISED IN THE DECLARATIVE SECTION:
If the declarative section raise an exception the exception is immediately propagates to the
enclosing block(not with in current block of EXCEPTION SECTION).
EXCEPTION RAISED IN THE EXCEPTION SECTION:
The exception is propagated to the enclosing block.
v_student t_studentrecord;
v_student1 t_studentrecord;
v_student2 t_studentrecord1;
referencing a Record:
v_student.first_name := 'asd';
Record assignment:
If both record of same type then
v_student := v_student1;
because records of diferent type
v_student1 := v_student2 -- illegal
but
v_student.first_name := v_student2.first_name -- legal as fields are same type.
assigning record to slect statement.
select first_name,last_name, currentcredits into v_student from students;
31)What is subtypes?
A subtype is used to give an alternatve name for a type(pl/sql also define subtype eg. decimal and integer
are subtype of number).
declare
subtype t_loopcounter is number
subtype t_loopcounter is number(4) --- illegal
v_dummyvar number(4)
subtype t_loopcounter is v_dummyvar%type
33)Null as an statement?
Null statement does not do anything it just serve as a placeholder.
Only sql statements allowed in pl/sql are dml and transaction control languages.This is because other sql
statements will alter the schema objects.
35)What is Binding?
It is the process of identifying the strorage location associated with an identifier in the program.In pl/sql it
also checks the permission to access the object reference.
36)What is dynamic sql?
A technique that allows all valid sql statements including DDL to be issued in pl/sql.there are two
technique in dynamic sql
a)Native dynamic SQL.
b)DBMS_SQL Package.
Until the block is completed the pl/sql will not create table so inserting values in that will cause error so
'EXECUTE IMMEDIATE' statement is used to avoid this error.
begin
execute immediate 'create table temp_table(num_value number, cahr_value char(10))';
execute immediate 'Insert into temp_table (num_values, cahr_vlue) values (10,"hellow")';
end;
39)What is ROWID?
The ROWID is a psedo column used in select list of a query.
It returns the row identifier of that particular row.
The ROWID psedocolumn returns a value of type ROWID
40)What is ROWNUM?
It return current row number in the query.
It is useful for limiting the total number of rows and it i used in the where caluse of query and set clause of
update statement.
Rownum return a number value.
EXAMPLE:
Select * from students where ROWNUM < 3;
43)What is transaction?
A transation is a series of sql statements that either succeeds or fils as units.
Used to prevent inconsistent of data.
A transaction begins with first sql statement.
Transaction ends with COMMIT or ROLLBACK.
When COMMIT ISSUED
a)All work done by the transaction is amde perment.
b)Other session can see the changes made by this transaction.
c)Any locks acquired by the transaction are released.
COMMIT [WORK]
WORK - optional available for increased readability.
When ROLLBACK issued
a)All work done by the transaction is undone
b)Any lock acquired by transaction are relesed.
c)Issued when error occurs
ROLLBACK [WORK]
SAVEPOINT:
With SAVEPOINT only part of transaction need be undone.
SAVEPOINT name
name - name of the SAVEPOINT.
Once SVEPOINT is defined it can be used in ROLLBACK as
ROLLBACK [WORK] TO SVEPOINT name
When issed
a)Any work done since the savepoint is undone, the sacepoint remains active.However it can be rollback
again
b)any lock nd resource acquired by the SQL statement since the save point is undone.
c)The transaction isnot finished because SQL statement are still pending.
Numeric Functions:
ABS(x) - reurns the absolute value of x;
BITAND(x,y) - returns bitwise AND of x and y,each of which must be non-negative inteer value. There is
no BITOR functions.
CEIL(X) - retruns smallest integer greater than or equal to x.
EXP(X) - Returns e raised to the xth power. e=2.71828183.
Floor(x) - returns the largest integer equal to or less than x.
MOD(x,y) - Returns the remainder of x divided by y, if y is 0,x is returned.
POWER(x,y) - Return x raised to yth Power.
ROUND(x,[,y]) - Returns x rounded to y placs to the rigth of the deciaml point. y defaults to 0. which
roundes to the nearest integer.
SIGN(x) - if x < 0 ,returns -1,if x=0 returns 0. if x>0 returns 1.
TRUNC(x,[,y]) - Return x truncatd to y dcimal places.
WIDTH_BUCKET(x,min,max,num_buckets) - allows to crate equal-length histograms based on the input
parameters. The range MIN and MAX is divided into num_buckets sections
Conversion function:
TO_CHAR - Converts its argument to a character type.
TO_DATE - Converts its argument to a date datatype.
TO_NUMBER - Converts its argument to a number type.
Other functions:
BFILENAME - Return the BFILE locator associated with the phyisacal file.
COALESCE - Return non - NULL expr in the argument list.
DECODE(base_expr,compare1, value1,compare2, value2 ... default) - Simiklar to nested IF-THEN-ELSE
EXTRACT(XML type_instance,Xpath_string) - Returns the portion of XML documnet identified by XML
type_instance after applying Xpath_strig
GREAST(expr1[,expr2]...) - Returns the greatest expression of its argument.Each expression is implicitly
converted to the type of expression1 before before the comparision are made.
LEAST(expr1[,expr2]...) - Returns the least value in the list of expression. LEAST behaves similarly to
GREATEST.
NULLIF(a,b) - Returns NULL if a is equal to b and a if they are not equal.
NVL(expr1,expr2) - If expre1 is NULL returns epr2; otherwise return expr1.
NVL2(expr1,expr2,expr3) - If expres1 is NULL the expre2 is returned;otherwise expr3 is returned
UID - Returns an integer that uniquely identifies the current database user.
USER - Retruns a varchar2 value containing the name of current oracle user.
What is collection?
Collections are composite types.
A collection combines variable of same type.
Three types of collections index by table nested table and varray.
In order to declare an index-by-table you first declare the table type and then declare a variable to that type.
TYPE tabletype IS TABLE OF type INDEX BY BINARY_INTEGER;
Once the type and variable is declared we can refer by following syntax.
Tablename(index);
Note:INDEX BY BINARY_INTEGER clause is required for index by table which is not presented for
nested table.
What is VARRAY?
A variable length array is a data type that had fixed upper bound on its size specified as a part of
declaration.
The elements are stored contiguously in memory this is different from the storage for a nested table.
The key must be positive.
Are constrained to maximum size in the type definition.
Always have space allocated for each elements and have sequential key value.
Can be automatically NULL.
VARRAY must be initialized before elements can be assigned.
It can be stored in database table.
When stored in database VARRAY can retain ordering and subscript value for the elements whereas nested
tables do not.
Declaring VARRAY:
TYPE typename IS {VARRAY| VARYING ARRAY} (maximum_size) OF element_type [NOT NULL];
VARRAY INTIALIZAION:
They are initialized using constructor.
Insert
The INSERT statement is used to insert a collection into a database row.Insert into class-material
values ('MUS',100,Booklist(3001,3002));
UPDATE
Update is used to modify a stored collection.
UPDATE library-catalog
SET checked-out=StudentList(10009)
WHERE catalog-number = 3002;
DELETE
Delete can remove a row containing a collection.
SELECT
SELECT required-reading
INTO v-Books
FROM class-material
WHERE department = p-Department
AND course = p-course;
What are Collection Methods and what are all different type of collection methods?
Nested tables and varrays are object types, and as such they have methods defined on them. Likewise,
index-by tables have attributes.
Syntax:
collection-instance.method-or-attribute
A function is very similar to a procedure. Both take parameters, which can be of any mode. A procedure
call is a PL/SQL statement by itself,
while a function call is called as part of an expression.
Subprogram Parameters
The formal parameters are the placeholders for the values of the actual parameters.
Mode
IN
The value of the actual parameter is passed into the procedure when the procedure is invoked. Inside the
procedure, the formal parameter acts like a PL/SQL constant-it is considered read-only and cannot be
changed. When the procedure finishes and control returns to the calling environment, the actual parameter
is not changed.
OUT
Any value the actual parameter has when the parameter is called is ignored. Inside the procedure, the
formal parameter acts like an uninitialized PL/SQL variable, and thus has a value of NULL. It can be
read from and written to. When the procedure finishes and control returns to the calling environment, the
contents of the formal parameter are assigned to the actual parameter.(In Oracle8i, this behaviour can be
altered by using the NOCOPY modifier-see the section "Passing Parameters by Value and by Reference"
later in this chapter.)
INOUT
This mode is a combination of IN and OUT. The value of the actual parameter is passed into the procedure
when the procedure is invoked. Inside the procedure, the formal parameter acts like an initialized variable,
and can be read from and written to. When the procedure finishes and control returns to the calling
environment, the contents of the formal parameter are assigned to the actual parameter(subject to NOCOPY
in Oracle8i, as for OUT).
What is NOCOPY?
Is an compiler hint.
If NOCOPY is present the compiler will try to pass the parameter by reference rather than by value.
Using NOCOPY in the in parameter will generate compilation error because IN parameter is always passed
by reference.
paramater_name [mode] NOCOPY datatype.
CREATE OR REPLACE PROCEDURE nocopytest(
p_inparameter IN NUMBER,
p_outparameter OUT NOCOPY VARCHAR2,
p_inoutparameter IN OUT NOCOPY CHAR) IS
What is PACKAGES?
A package is a PL/SQL construct that allowed related objects to be stored together. The packaaged have
two separate parts.
The package specification
The package Body.
Each of it is stored separately in data dictionary.
Difference between serially reusable package and non serially reusable package?
Serially Reusable Packages
Runtime state is kept in shared memory, and is freed after every database call.
The maximum memory used is proportional to the number of concurrent users of the package.
Non serially Reusable Packages
Runtime state is kept in process memory, and lasts for the life of the database session.
The maximum memory used is proportional to the number of concurrently logged-on users, which is
typically much higher.
userA creating procedure based on table userB.temp_table have to grant access to userB on procedure OR
stored subprograms?
userA must have granted SELECT privilages on temp_table.
This grant must be done explicitly and not through a role. This is also applied to triggers and packages that
are stored in database as well. Else an error will be through.
This is because PL/SQL uses early binding that is referencing objects at compile time not runtime.
GRNAT and REVOKE are both DDL statements they take effect immediately and new privileges are
recorded in data dictionary. All database sessions will see the new privilege set. However this is not
necessarily true for roles. A role can be granted to a user and that user can then chose to disable the role
with the SET ROLE command. The distinction is that SET ROLE applies to one database session only
while GRANT and REVOKE will apply to all sessions. A role can be disabled in one session but enable in
other session.
In order to allow privileges granted via a role to be used inside stored subprogram and triggers, the
privilages wolud have to be checked every time the procedure is run. The privileges are checked as part of
the binding process. But early binding means that the privileges are checked at compile time not run time in
order to maintain early binding all roles are disables inside stored procedure, functions, packages and
triggers.
Invoker's Vs Definers Rights
if userA and userB have own copy of temp_table and EXECUTE privileges are given to userB on
procedureA created by user then userA's temp_table is affected this is called Definer's rights.
Because unqualified external reference within it are resolved under the privilage set by owner or
definer.
In an invokers rights subprogram, external reference are resolved under the privilege set of the caller not
the owner.
An invokers rights routine is created by using AUTHID clause. It is valid for stand alone subprogram
package specification and object type specification.
Individual subprogram within a package must be all invokers or definers not a mix.
AUTHID [CURRENT_USER|DEFINER]
A database trigger will always be executed with the definers right and will execute under the privilege set
of the schema that owns the triggering table. This is true for pl/SQL functions that is called from view.
How stored functions used in SQL? Or what is purity level
Depending on where a use-defined function is used and what version of oracle you are running it must meet
different restrictions. These restrictions are defined in terms of purity level.
There are four different purity levels
Why is RESTRICTED_REFERENCE is used for Package functions and not for stan alone functions?
The PL/SQL Engine need PRAGMA to check the purity level of the packaged function, to verify that it is
being used correctly in the calling block. Whenever the package body is modified the function code is also
checked against the pragma. The pragma is checked at compile time and not run time.
For overloading functions the pragma is applies to the nearest definition prior to the declaration.
For oracle8i and above if the pragma is not specified the database will verify the purity level at run time.
What is Triggers?
Triggers are similar to procedures and functions.
Like packages triggers are stored in database. It cannot be local to package or block.
A trigger is executed implicitly whenever the triggering event happens and it wont accept any arguments.
The act of executing the trigger is called firing the trigger.
:new is modified only in before row-level trigger and :old is never modified.
:old and :new have no meaning in the statement level trigger.
:old and :new cannot be passed to procedure or function that take arguments of triggering_table%rowtype.
What is referencing clause?
It is used to specify different name for :new and :old. This is present after the triggering event, before the
WHEN clause, syntax
REFERENCING [OLD AS old_name][NEW as new_name]
Old and new are without COLON inside the referencing clause.
You must have the ADMINISTER DATABASE TRIGGER system privilege in order to create a system
trigger.
What are the system DDL and DATABASE Events?
STARTUP
--AFTER
--Fired when an instance is started up.
SHUTDOWN
--BEFORE
--Fired when an instance is shutdown. This event may not fire if the database is shutdown abnormally (as in
a shutdown abort).
SERVERERROR
--AFTER
--Fired whenever an error occurs.
LOGON
--AFTER
--Fired after a user has successfully connected to the database.
LOGOFF
--BEFORE
--Fired at the start of a user logoff.
CREATE
--BEFORE, AFTER
--Fired before or after a schema object is created.
DROP
--BEFORE, AFTER
--Fired before or after a schema object is dropped.
ALTER
--BEFORE, AFTER
--Fired before or after a schema object is altered.
STARTUP and SHUTDOWN triggers are relevant only at database level it is not illegal to create them at
the schema level but they will not fire.
If an INSERT statement affects only one row, the before and after row triggers for that row do not treat the
triggering table as mutating. This is the only case where a row-level trigger may read from or modify the
triggering table. Statements such as INSERT INTO table SELECT... always treat the triggering table as
mutating, even if the subquery returns only one row.