Академический Документы
Профессиональный Документы
Культура Документы
Ankita Kachwaha
Disadvantages of SQL
No procedural capabilities. SQL statements are passed to oracle engine one at a time. No facility to handle errors.
Advantages of PL/SQL
Provide facility of condition checking, looping, and branching. Entire block of statement is passed to oracle engine. Permit dealing with errors. All sort of calculation can be done quickly and efficiently. PL/SQL blocks are portable.
PL/SQL block
DECLARE
BEGIN EXCEPTION END;
BEGIN
EXCEPTION
END;
DECLARE (Optional)
Variables, cursors, user-defined exceptions
BEGIN (Mandatory)
END; (Mandatory)
Execution environment
PL/SQL engine PL/SQL block PL/SQL PL/SQL block SQL Procedural statement executor
Character set
Variable declaration
Scalar type Composite type LOB type Reference type Object type
Scalar type
stored value
1234.678 123 error error- exceed precision 1.235 12345.67 1000
Char Varchar2 Date Long Long raw/raw Boolean (true, false, null)
Composite type
Packages
LOB type
REFERENCE TYPE
CURSOR
OBJECT TYPE
% type This declares a variable of the same type as previously defined variable or column of a table or view. Identifier Table.column_name%TYPE; v_min_balance v.balance%TYPE := 10;
Variable
Must begin with character and have maximum length of 29. Reserve words can be used as variable but must be enclosed in double quote. Spaces and special symbol not allowed except underscore. Var_name data type(size) [default value]; Var_name data type(size)[ :=value];
Constraint
Displaying messages
DBMS_OUTPUT is a package. PUT_LINE is a procedure which accept only single parameter of character type. Set serveroutput on;
Comment
-/**/
SQL> SET SERVEROUTPUT ON SQL> SQL> BEGIN 2 DBMS_OUTPUT.PUT_LINE(4 * 2); 3 DBMS_OUTPUT.PUT_LINE(24 / 3); 4 DBMS_OUTPUT.PUT_LINE(4 + 4); 5 DBMS_OUTPUT.PUT_LINE(16 - 8); 6 END; 7 / 8 8 8 8
SQL> set serveroutput on SQL> declare 2 v_length NUMBER :=5.5; 3 v_width NUMBER :=3.5; 4 v_area NUMBER; 5 begin 6 v_area:=v_length*v_width; 7 DBMS_OUTPUT.put_line('Area:'||v_ar ea); 8 end; 9 / Area:19.25
SQL> declare 2 v_name VARCHAR2(256); 3 begin 4 select first_name 5 into v_name 6 from employee 7 where id=7; 8 DBMS_OUTPUT.put_line('v_name:'||v_name); 9 10 end; 11 / v_name:David
Scope Rules
Scope means the range of code within which a given identifier can be referenced. An identifier can be referenced only by code executing inside the block in which the identifier was declared. An identifier could be a variable name, or a procedure name, function name.
SQL> declare 2 v_custno NUMBER := 100; 3 begin 4 dbms_output.put_line(v_custno) ; 5 declare 6 v_state CHAR(2):= 'NY' ; 7 begin 8 dbms_output.put_line(v_custno || v_state) ; 9 end ; 10 end ; 11 / 100 100NY
dbms_utility.get_time
Conditional control
If <condition> then <action> elsif <condition> then <action> else <action> end if;
Example
Declare cur_bal number(10,2); acno number(4); Begin select bal into cur_bal from acct where acctno=141; if cur_bal < 5000 then update acct set bal=bal-100 where accno=141; end if; End;
Type of loops
Simple loop
Example
Declare i number:=0; Begin loop i:= i+2; exit when i>10; end loop; dbms_output.put_line(loop end when i=||to_char(i)); End;
While loop
example
Declare pi constant number(4,2):=3.14; radius number(5); area number(14,2); begin while radius <=7 Loop Area:=pi*power(radius,2); Insert into areas values (radius, area); radius:=radius+1; end loop; End;
For loop
Example
Declare no varchar2(5):=65432; str_len number(4); reverse varchar2(5); Begin str_len:=length(no); for count in reverse 1..str_len loop reverse:=reverse||substr(no,count,1); end loop; dbms_output.put_line(reverse no is ||reverse); End;
Goto statement
Example
Declare no number(5); Begin no:=&no; if no>5 then goto mark; end if; dbms_output.put_line(more than 5); <<mark>> End;
Restriction on go to
Begin goto inner block; -- illegal cannot branch to an inner block begin .. <<inner block>> .. end; goto innerif ; -- illegal cannot branch into an if statement if 9>3 then . <<innerif>> .. end if; end;
Begin if 9>3 then goto next; -- illegal to branch from one if clause to another else <<next>>; end if; end;
Labeling
Labeled statement
Labeled block
<<block1>> declare rno number(5); begin rno:=&rno; select * from std where rno=block1.rno; <<block2>> begin end; end;
<<o>> declare i number(2):=1; begin dbms_output.put_line(i); <<ii>> declare i number(2):=10 ; begin dbms_output.put_line(o.i); dbms_output.put_line(ii.i); dbms_output.put_line(i); end; end;
Oracle tractions
Transaction is series of operation perform on DB. Following events take place connecting to oracle committing changes to DB rollback disconnecting from DB
Atomicity Transactions are committed or rolled back as a group, and are atomic, meaning that all SQL statements contained in a transaction are considered to be a single indivisible unit. Consistency Transactions ensure that the database state remains consistent, meaning that the database starts at one consistent state and ends in another consistent state when the transaction finishes. Isolation Separate transactions should appear to run without interfering with each other. Durability Once a transaction has been committed, the database changes are preserved.
Commit
Commit;
Rollback
Ends the transaction. Undoes all the changes. Erase all save point in that transaction. Release the transaction lock.
Example
Declare no number(5); Begin no:=&no; savepoint no_update; update emp set sal=sal+no; if no>5000 then rollback to savepoint no_update; end if; commit; End;
Flashbacks
If you mistakenly commit changes and you want to view rows as they originally were, you can use a query flashback . EXECUTE DBMS_FLASHBACK.ENABLE_A T_TIME(SYSDATE - 10 / 1440);
Declare type stdrec is record( rno number(3), name varchar2(10), per number(4,2)); s1 stdrec; begin s1.rno:=10; s1.name:=xyz; s1.per:=68; end;
declare fid UTL_FILE.FILE_TYPE := UTL_FILE.FOPEN (loc , file, 'R'); line VARCHAR2(2000); BEGIN DBMS_OUTPUT.PUT_LINE (file); LOOP UTL_FILE.GET_LINE (fid, line); DBMS_OUTPUT.PUT_LINE (line); exit when no_data_found; END LOOP; end;
Writing on a file
declare fid UTL_FILE.FILE_TYPE := UTL_FILE.FOPEN (lo c, file, w'); v VARCHAR2(2000); BEGIN v:=vdvfdbfbd; UTL_FILE.PUT_LINE (fid, v); UTL_FILE.FCLOSE (fid); end;
Cursor
The oracle engine uses a work area for internal processing in order to execute an sql statement. Active data set.
Type of cursor
IMPLICIT CURSOR.
Oracle engine open this cursor and manage it. The value of this cursor always refer to most recently executed sql statement.
Example
Begin update acct set bal=bal+5000 where acno=141; if sql%notfound then dbms_output.put_line(error in updation); end if; End;
Begin for cur1 in(select rno, name, per from std where per >=60) loop insert into std1 values(cur1.rno, cur1.name, cur1.per); end loop; end; /
Explicit cursor
No Yes DECLARE OPEN FETCH EMPTY? CLOSE
Create a
named SQL area
Identify
the active set
Load the
current row into variables
Test for
existing rows
Release
the active set
Return to
FETCH if rows are found
2. Fetch a row using the cursor. Cursor pointer Continue until empty. 3. Close the cursor. Cursor pointer
Cursor declaration
A cursor is defined in declarative part of a pl/sql block. Cursor <cursor name> is select statement;
Opening a cursor
Closing cursor
Example
DECLARE v_empno employees.employee_id%TYPE; v_ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO v_empno, v_ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empno) ||' '|| v_ename); END LOOP; CLOSE emp_cursor; END ;
Cursor example
Declare cursor c1 is select name, sal from emp; name emp.name%type; sal emp.sal%type; Begin open c1; loop fetch c1 into name, sal; exit when c1%notfound; dbms_output.put_line(name|| ||to_char(sal)); end loop; End;
%rowtype
Declare cursor c78 is select rno, name, per from std1 where name like a%; varcur c78 %rowtype; begin open c78; fetch c78 into varcur; while c78%found loop dbms_output.put_line(varcur.rno || || varcur.per); fetch c78 into varcur; end loop; end; /
Illegal fetch
For <variable> in <cursor name> Here for loop variable is automatically created of %rowtype.
Implicitly declared its loop index as a %rowtype record. Open a cursor. Fetch a row from cursor for each loop iteration. Closes the cursor when all the rows have been processed.
Example
Declare cursor c2 is select eid, sal from emp where deptno=20; Begin for emp_rec in c2 loop update emp set sal=emp_rec.sal+1000; end loop; commit; End;
Parameterized cursor
Example
Declare cursor c_emp (No NUMBER) is select count(*) from employee where deptno = No; deptNo employee.deptno%type:=10; countEmp NUMBER; Begin open c_emp (deptNo); fetch c_emp into countEmp; close c_emp; dbms_output.put_line(to_char(countEmp)); End; /
Cursor c1 is select name, per from std for update; Any changes are not reflected to DB if update clause is not specified.
Commit must be used after all fetch statement in case of update cursor. If used inside loop than it will release all the locks and any further fetch will fail.
Reference cursor
SQL> declare 2 c1 sys_refcursor; 3 abc a%rowtype; 4 begin 5 open c1 for select no from a ; 6 loop 7 fetch c1 into abc; 8 exit when c1%notfound; 9 dbms_output.put_line(abc.no); 10 end loop; 11 close c1; 12 end; 13 / 1 11 111 1111 PL/SQL procedure successfully completed.
Type tab1 is table of std.per%type; Type tab2 is table of std%rowtype; Type tab3 is table of number index by binary_integer; Type tab4 is table of date index by binary_integer;
Example
Declare type notab is table of number index by binary_integer; v1 notab; Begin for v2 in 1..10 loop v1(v2):=v2*10; end loop; Dbms_output.put_line(table elements are); for v2 in 1..10 loop Dbms_output.put_line(v1(v2)); end loop; End; /
Varray
Example
Declare Type no is varray (20) of number(3); V1 no; V2 no:= no(11,22); V3 no:=no (null); Begin if v3 is null and v1 is null then dbms_output.put_line(null); End if; V2(1):=& V2(1); V2(2):=& V2(2); End; /
Pl/sql security
For concurrency control locking method is used. Implicit locking Explicit locking
Type of locks
Level of lock
Explicit locking
Client a> select * from std where rno=10 for update; Record will be locked and released when commit or rollback is fired. Client b> select * from std where rno=10 for update; Client a> select * from std where rno=10 for update nowait;
Lock table
Lock table <tn1> [,<tn2>,.] in {row share | row exclusive | share update | share | share row exclusive | exclusive } [nowait]
Releasing lock
Deadlock
Transaction 1 begin update std set per=90 where rno=10; update std set per=50 where rno=20; end; Transaction 2 begin update std set per=50 where rno=20; update std set per=90 where rno=10; end;
Exception handling
Exception condition Exception handler Named exception(15-20) Numbered exception(20000) Default exception handling
Error type
Error type Compile time reported by pl/sql compiler handled by compiler report error exception handler
Runtime
Syntax
Exception when <exception name> then <user specified action>
Named exception
TIMEOUT_ON_RESOURCE TRANSACTION_BACKED_OUT INVALID_CURSOR ZERO_DIVIDE INVALID_NUMBER (eg char to number) STORAGE_ERROR VALUE_ERROR (eg conversion, truncation error) ROWTYPE_MISMATCH CURSOR_ALREADY_OPEN COLLECTION_IS_NULL SUBSCRIPT_OUTSIDE_LIMIT SUBSCRIPT_BEYOND_COUNT CASE_NOT_ FOUND
EXAMPLE
Declare v1 std.per % type; Begin select per into v1 from std where rno=10; dbms_output.put_line(v1); Exception when no_data_found then dbms_output.put_line(no record found); End;
Example
Declare v1 std.per % type; v2 std.rno %type; resource_bsy exception; pragma exception_init(resourse_bsy,-00054); Begin update std set per=&v1 where rno=&v2; Exception when resource_bsy then dbms_output.put_line(row is used by other); End;
Example Declare
r std.rno %type; n std.name % type; p std.per %type; temp number(2); e1 exception; Begin r:=&r; n:=&n; p:=&p; Select count(rno) into temp from std where rno =r; If temp = 0 then insert into std values(r,n,p); else raise e1; end if; Exception when e1 then dbms_output.put_line(error in insertion); End;
SQL> BEGIN DBMS_OUTPUT.PUT_LINE(1 / 0); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An exception occu rred'); WHEN ZERO_DIVIDE THEN DBMS_OUTPUT.PUT_LINE('Division by zero'); END; / WHEN OTHERS THEN * ERROR at line 4: ORA-06550: line 4, column 4: PLS00370: OTHERS handler must be last among the e xception handlers of a block
Inside others handler it is often useful to know which oracle error raise exception. Sqlcode returns current error code. Sqlerrm return error message text.
Example
Declare v1 std.rno % type; Begin select rno into v1 from std; Exception when others then dbms_output.put_line (sqlcode || sqlerrm); End;
Raise_application_error (no, msg ); No can be between -20000 and -20999 Msg can be 512 characters
Example
Declare temp number(5); Begin select count (rno) into temp from std; if temp <1 then raise_application_error(-20001,no student data available); end if; End;
Error propagation
If current block has a handler for exception than execute it and complete the block successfully. Later on control is passed to enclosing block. If there is no handler for the exception than propagate it to the enclosing block which will handler it if handler is define for that exception otherwise default exception handler will handle the exception.
a exception;
Begin Begin raise a; Exception when a then . End; End; Exception a is handled in sub block
Begin raise b; Exception when a then . End; Exception when b then End; Exception b is propagated to outer block and handled there No handler for b in sub block
Declare a exception; b exception; c exception; Begin Begin raise c; Exception when a then . End; Exception when b then End; Exception c is propagated to outer block but there is no handler Exception will be handled by default handler No handler for c in sub block Exception c is raised in sub block
Value error
Begin
Value error
Declare num number(3):=abc; Begin Exception when others then .. End; Exception when others then . . End; Outer block exception handler will handle it Even others handler exist in inner block it is not executed
Declare a exception; b exception; Begin raise a; Exception when a then raise b; when b then .. End; Exception b is raised Even though there is a handler for b here, it is not executed. The exception is propagated out of block Exception a is raised
Begin Declare a exception; b exception; Begin raise a; Exception when a then raise b; when b then .. End; Exception when b then End; Exception b is handled here Exception is handled and b is raised Even though handler for b exist still it will propagate out of block Exception a is raised
Exception a is raised Declare a exception; Begin raise a; Exception when a then . raise; End; Same exception is raised again Exception a is handled
These are set of sql and pl/sql statement that perform specific task. Consist of 3 parts declarative part executable part optional exception handling part
Stored in oracle database Invoked by any pl/sql block Before saving procedure or function oracle engine parses and compiles it. If error occur during compilation invalid procedure or function is created.
Steps of execution
Verify user access Verify procedure or function validity Executes procedure or function
Advantages
Function can return a value back to calling point. A function can return only one value to calling point. By defining multiple out parameter in procedure multiple values can be passed to calling point. A procedure call is a pl/sql statement while function call is a part of an expression.
Syntax of procedure
Create or replace procedure [schema.]<name> (<argument>{in,out,in out}<data type>,){is,as} <variable constant declaration>; Begin .. Exception End;
Syntax of function
Create or replace function [schema.]<name> (<argument>in<data type>,) Return <data type> {is,as} <variable constant declaration>; Begin .. Exception End;
Return statement
There can be more than one return statement in a function although only one of them will be executed. It will be an error if there is no return statement in a function.
Example
Create or replace function f1 (sal1 in number) Return number is Temp number(5); Begin select count (eid) into temp from emp where sal > sal1; return temp; End;
Example procedure
Create or replace procedure p1(rnoo in number, namee in varchar2, perr number) is Begin insert into std values(rnoo, namee, perr); End;
Declare namee std.name %type:=abc; rnoo std.rno %type:=10; perr std.per %type:=70; Begin p1(rnoo, namee, perr); End;
Parameter of procedure
Mode
In
The value of actual parameter is passed into procedure when procedure is invoked. Inside procedure formal parameter act like pl/sql constraint and cant be changed.
Out
Any value actual parameter has when procedure is called is ignored. Inside the procedure formal parameter act like un-initialized pl/sql variable and has null value. When procedure finishes and control return to calling environment content of formal parameter are assigned to actual parameter.
In out
This is combination of in out. The value of actual parameter is passed into procedure when procedure is invoked. Inside procedure formal parameter act like an initialized variable and can be read and written. When the procedure finishes control return to calling environment and content of formal parameter are assigned to actual parameter.
Example
create or replace procedure p1 ( v1 in number, v2 out number, v3 in out number) is lv1 number:=0; begin lv1:=v1; /* v1:=4 ; error */ v2:=4; /* lv1:=v2; error */ v3:=v3+v3; end;
SQL> declare 2 v11 number:=11; 3 v22 number:=22; 4 v33 number:=33; 5 begin 6 p1(v11,v22,v33); 7 dbms_output.put_line(v11|| ||v22|| ||v33); 8 end; 9 / 11 4 66 PL/SQL procedure successfully completed.
If procedure or function has no exception handler for the exception condition than control immediately passes out to the calling program i.e. calling environment in accordance with exception propagation rule.
Package
Package is oracle object which hold other objects within it. Allow efficient organization of commercial application Allow granting of privileges efficiently Enable overloading of function and procedure Improves performance by loading multiple objects into memory. Promote reuse of code.
Package specification
Name of the package Name of the variable and data type This declaration is local to the DB and local to the package.
Package declaration
Create package pack1 is function f1(v1 in varchar2) return number; procedure p1(v2 in varchar2, v3 in varchar2); End pack1;
Package body
Create or replace package body pack1 as function f1(v1 in varchar2) return number begin exception end; procedure p1(v2 in varchar2, v3 in varchar2) begin exception .. end; End pack1;
Invoking a package
Verify user access. Checks that procedure is valid or not if not than it is automatically recompiled. The package subprogram is executed.
Package_name.type_name
Package_name.object_name
Package_name.subprogram_name
Any item declared within package specification are public i.e. visible outside the package. All items declared inside package body are private.
Functions with same name but different parameters are called overloaded function. Create or replace package check is function ok (date1 in date) return number; function ok (num in number) return number; end check;
Create or replace package body check is function ok (date1 in date) return number begin if date1< sysdate then return 1; else return 0; end if; end; function ok (num in number) return number begin if num<10 then return 0; else return 1; end if; end; End check;
Calling
Begin if check.ok(22) = 1 then dbms_output.put_line(number is greater than 10); end if; End;
Restriction
Overloading procedure or function cant have same number of parameters with different name and different mode but same data type.
Overloading functions or procedures with same parameter name , mode and data type but different return type are not permitted. All the overloaded modules must be defined within same scope or block.
Trigger
Trigger are the implicit procedure that are implicitly executed when insert, update, delete is issued against a table.
Use of trigger
A trigger can permit DML statement against a table only if they are issued during regular business hours. It can be used to prevent invalid transaction. Enforces complex security. It can also be used to keep track of updated or deleted records.
Cascading trigger
When a trigger is fired sql statement inside trigger can also fire some other trigger. This is called cascading trigger.
Trigger do not accept parameter whereas procedure can. Trigger is executed implicitly by oracle engine itself upon modification of an associated table. To execute procedure it has to be explicitly called by user.
Integrity constraint is a statement about DB that is always true. Trigger contain what a transaction can do i.e. trigger do not apply to data loaded so it don't guarantees that all the data in the table confirms rules.
Type of trigger
Row triggers fired each time a row in the table is affected. E.g. update statement changes multiple rows than trigger is fired for each row.
Statement trigger
Fired once on behalf of triggering statement. Independent of number of rows affected. Used when processing is required which is independent of number of rows affected.
Before triggers
Before trigger determine whether or not triggering statement should be allowed to complete.
After trigger
Combinations
Before statement trigger Before row trigger After statement trigger After row trigger
Syntax
Create or replace trigger <name> {before, after} {delete, insert, update [of column.,..]} On <table name> [referencing {OLD as old, NEW as new }] [for each row [when condition]] Declare Begin .. Exception End;
Create trigger audit after update or delete on cust for each row Declare Op varchar(20); Begin if updating then op:=update Elsif deleting then op:=delete; End if; Insert into cust_backup values(:old.cust_id, :old.name, :old.sal, user, sysdate); End;
Three categories
DML trigger
This trigger is fired by a DML statement. DML trigger can be defined for insert, update or delete operation.
Instead-of trigger
These triggers can be defined only on views. Instead of trigger will be executed instead of DML statement. Instead of trigger must be row level.
Example
Create or replace view class as select dept, building, roomno from classes where building=bcom; Insert into class values(sci, be, 10);
Create or replace trigger classtrigger Instead of insert on class Declare Temp number(3); Begin select count (roomno) into temp from classes where roomno=10 and building=be; if temp=0 then Insert into classes values(sci, be, 10); else dbms_output.put_line( insert not possible); end if; End;
System trigger
System trigger fires when a system event such as DB startup or shut down occurs. System trigger can also be fired on DDL statement
Create or replace trigger logcreate After create on schema Begin insert into db_tab (user_id, object_type, object_name, object_owner, createion_date) values (user, sys.dictionary_obj_type, sys.dictionary_obj_name, sys_dictionary_obj_owner, sysdate); End;