Professional Documents
Culture Documents
#################### # PL/SQL # #################### Before going to start PL/SQL first we will discuss what is sql and pl/sql SQL: It is a structured query language AND non-procedural language PL/SQL: It is a procedural language. we can communicate with the database directly using SQL. In sql we have some sublanguages DDL -> Data Definition language |-> Create |-> Alter |-> Rename |-> Drop |-> Truncate DML -> Data Manipulation Language |-> Insert |-> Update |-> Delete DCL -> Data Control Language |-> Grant |-> Revoke TCL -> Transaction Control Language |-> Commit |-> Rollback |-> Savepoint DQL/DRL -> Data Query/Retrieval Language |-> Select Differences between Delete and Truncate _________________________________________________________________ | DELETE | |---------|1. It is a DDL Statement | |3. Whole records of table will be | deleted perminantly TRUNCATE | | | | | | | |--------------------------| 1. It is a DML statement | | commit or rollback completeset of records
| 2. Explicitly user has to Perform |2. It is Auto-commited statement | 3. Deletion may be partial or`
Page 1
| 6. Estimated time is proportional |6. Estimated time is independent of| | to the amount of data is handling | | 7. Space will not be released as | | Mark there is no change in High Water | | |_____________________ ______ |7. space will be released as the
|____________________________
[3]. In Delete Command Partial is nothing but where deptno=10 only 3 records will be deleted In Truncate command all the records of the table will be removed Perminantly [5]. For ex: if i am delete 10000 records from the table, the before image data has to store in undo tablespace if the undo tablespace doesnt have enough space to handle the before image the txn will not complete, it will be rolled back. And i am trying to delete the records which are not present in my Actual table then instead of getting error i will get a message "No rows selected" In this two cases we can say that the txn is fail But in truncate there is no use of undo tablespace because the records will deleted perminantly and no where the before image will store. [6]. Estimated time is dependent because the before image has to write to undo tablespace in delete statement But in truncate with in fraction of secons the records will removed How to check Defragmentation? Basha>>select avg_row_len,num_rows from dba_tables where table_name='EMP'; Basha>>alter table emp move to <othertsname>; ##########Real time Scenarios where we have to use PL/SQL only############ 1. Log in and logout time of a user
Page 2
Page 3
4> Exception handling -> Note: in pl/sql an error is called as an exception, pl/sql permits dealing with errors as required and facilitates displaying user friendly messages when errors are encountered. 5> Portability( platform independent) -> applications written in pl/sql are portable to any computer hardware and operating system where ever oracle server can run, without any modifications at all 6> Supports Subprograms: -> pl/sql supports to share & reuse the code through subprograms using named pl/sql blocks here procedures and functions are known as subprograms. PL/SQL BLOCK / \ NAMED BLOCK UN-NAMED OR ANONYMOUS Named: These blocks are possible to store in the db by giving a name to block. --> calling the named pl/sql block is possible. Unamed or anonymous: Storing un-named or anonymous blocks is not possible --> calling un-named pl/sql block is not possible Pl/sql block contains 3 Sections: 1) Declaration Section 2) Executable Section 3) Execptional handling section Declaration Section: its an optional section in this section we declare variables, cursors, exceptions, constants,..etc Executable Section: it is a manadatory section
Page 4
Page 5
Page 6
Page 7
Commenting In pl/sql: -> To Comment a single line '--' is used -> To comment list of lines '/*....*/'
Using Select Statement in Pl/sql Block: Select col1,col2,col3... into var1,var2,var3 from <table_name> where <cond>; ex1: declare v_ename varchar2(10); begin select ename into v_ename from emp where empno=7788; dbms_output.put_line(v_ename); end; / |-----------------------------------------------------------| |l or L or ; -> to view recently executed code. | |-----------------------------------------------------------| ex2: declare ename varchar2(10); sal number; job varchar2(10); hiredate date; begin select ename,sal,job,hiredate into ename,sal,job,hiredate from emp where empno=7788; dbms_output.put_line(ename||' '||sal||' '||job||' '||hiredate); end; /
Page 8
Page 9
Page 10
Page 11
Conditional Control Structures: Using a particular condition controling the number of executions is possible using conditional control structures.
1). Simple If: syntax: if<condition> then sequence of statements; end if; ex: declare n number:=&n; begin if n>=1 then dbms_output.put_line('positive'); end if; end; / 2). If-Else. Syntax: if <condition> then sequence of stmts1; else sequence of stmts2; end if; / ex: declare n number:=&n; begin
Page 12
Page 13
Question: Increase the employees salary who sal is less than 3000 declare v_empno number:=&v_empno; v_sal number; begin select sal into v_sal from emp where empno=v_empno; dbms_output.put_line('old salary is'||v_sal); if v_sal<3000 then update emp set sal=sal+200 where empno=v_empno; commit; select sal into v_sal from emp where empno=v_empno; dbms_output.put_line('new salary is'||v_sal); else dbms_output.put_line('no updations'); end if; end; / Local Variables & Global Variables: declare a number:=10; begin dbms_output.put_line(a);
Page 14
Page 15
Ex: Print 1 to 5 numbers using simple loop declare n number:=1; begin loop exit when n>5 dbms_output.put_line(n); n:=n+1; end loop; end; / While Loop: Syntax: while <condition> loop sequence of stmts; end loop;
Page 16
Syntax: for loopcounter in lowerbound..upperbound loop sequence of stmt; end loop; ex: Print numbers from 1 to 7 begin for i in 1..7 loop dbms_output.put_line(i); end loop; end; / Print number from 1 to 7 in reverse begin for i in reverse 1..7 loop dbms_output.put_line(i);
Page 17
Ex: Print as below given * * * * * * * * * * * * * * * * * * * * * * * * * declare n varchar2(20); begin for i in 1..5 loop for j in 1..i loop n:=n||'*'; end loop; dbms_output.put_line(n);
Page 18
Ex: Print the output as ---* --*** -***** ******* declare v varchar2(100):='*'; n number:=1; j number:=3; a char(200); spac varchar2(100); spac_1 number; begin loop exit when n>5; for k in 1..j loop spac:=spac||'-'; end loop;
Page 19
1. Implicit cursors: Declared for all pl/sql DML, pl/sql select statements. ex:(for dml) begin update emp set sal=sal+200; delete from emp where deptno=10; end; ex: (for select) declare n number; begin select ename into n from emp where empno=7900; end; / ex1: begin delete from emp;
Page 20
Page 21
Page 22
|___________| Note: The explicit Cursor always points to first record of the o/p.
******* DECLARING THE CURSOR ********* Declaration: cursor <cursor_name> is <select stmt>; opening Cursor: open <cursor_name>; Fetching: Fetch <cursor_name> into [(var1,var2,....)/record name]; Closing: close <cursor_name>; ******** Cursor States *******
Page 23
*********** Explicit Cursor Attributes ***** cur_name%isopen: Evaluates to true if the cursor is open cur_name%notfound: Evaluates to true if the most recent fetch doesnt return a row cur_name%found: Evaluates to true if the most recent fetch returns a row. cur_name%rocount: Returns the Numeric value of fetched Records
Ex1: declare n number; cursor c1 is select sal from emp where empno=7788; begin open c1; fetch c1 into n; dbms_output.put_line(n); close c1; end; / Ex2: declare v_ename varchar2(10); v_sal number;
Page 24
Page 25
Page 26
Page 27
Page 28
ex2: Print emp records without cursors. begin for i in(select *From emp) loop dbms_output.put_line(i.empno||i.ename||i.sal); end loop; end; /
Page 29
|4. Performance is better than|4. Poor Performance compared to |5. %rowcount give the no.of ex: 10 |5. %rowcount give the no.of rows | | |
|______________________________________
Page 30
Page 31
Page 32
Page 33
Page 34
Managing Predefined Exceptions: declare n number; begin delete from emp; select sal into n from emp where empno=&empno; dbms_output.put_line(n); exception when no_data_found then dbms_output.put_line('no records found with empno'); commit; end; / Semi Predefined Exceptions: In this semi predefined exceptions oracle will have the error code but error message will not be there. the user has to provide error message for error code. Ex1: declare e_notnull exception; pragma exception_init(e_notnull,-1400); begin insert into emp(empno,ename) values(null,'&ename'); commit; exception when e_notnull then dbms_output.put_line('you can not leave a field blank at empno'); end;
Page 35
Page 36
*********** SUB PROGRAMS Sub programs are devided in to two types: 1. Procedures 2. Functions
***************
Page 37
Page 38
--- procedure. --IN OUT:if the parameter is in out mode then a user can pass a value to the --value to the user. NOTE: Do not specify any size to datatype. IS/AS: used to start the pl/sql block. Using In mode parameter: create or replace procedure inmode(a number,b number) as s number; begin s:=a+b; dbms_output.put_line(s); procedure and from the same we can use the parameter to send a
Page 39
Page 40
Page 41
Page 42
Page 43
--> A function is a named pl/sql block that returns a value --> A function will store in the database as a schema object for repeated executions syntax: create or replace function <fun_name> [parameter1 <mode> datatype, parameter2 <mode> datatype, . . . ] return datatype is/as pl/sql block; Note: The pl/sql block should have atleast one return statement. ex: create or replace function sunfun(a number, b number) return number as begin return(a+b); end; / Using the function: sql>> select sumfun(10,40) from dual; Function with bind variables: sql>>variable a number; sql>>exec :a:=sumfun(10,40) sql>>print a o/p: 50 Using function in a block: sql>>declare
Page 44
select sumfun(empno,deptno) from emp; Ex: Create function to print day of given date: create or replace function fun1(f_date in date) return varchar2 is v_day varchar2(20); begin select to_char(f_date,'Dy') into v_day from dual; return v_day; end; / Ex: declare a number:=&a; b number:=&b; begin if sumfun(a,b)>100 then dbms_output.put_line('value is >100'); else dbms_output.put_line('value is <100'); end if; end; /
Page 45
Write a function to find tax depending on sal: create or replace function tax_cal(p_value in number) return number is begin return(case when p_value between 2000 and 5000 then p_value*0.1 when p_value between 100 and 1999 then p_value*0.04 else p_value end ); end tax_cal; / Differences b/w procedures and functions: --------------------------------------------------------------------------| PROCEDURE | FUNCTION |------------------------------------------------------------------------|1. Executes as a pl/sql stmt |2. No return clause in the header | |3. can return one or more or none | | values |4. can contain a return stmt |1. Invokes as a part of an expression| |2. Must contain a header clause in | | |3. Must Return a single value |4. Must contain at least one return | stmt. the header | | | | | | |
|______________________________________________________________________
######### PACKAGES
#############
--> A package is a collection of stored procedures and functions --> Inter-related procedures should be given in a package A package contains package specification and package body. Package specification: In package specification specifiy only the procedures and functions along with parameters without any executable sections.
Page 46
Note: With out creating a package specification creating package body is not possible Syntax to create package specification: create or replace package <package_name> is/as procedure 1 <procedure_name>(parameters <mode> datatype,....); procedure 2 <procedure_name>(parameters <mode> datatype,....); . . . function <function_name>(parameter <mode> datatype) return datatype; end package; / Syntax to create package body: create or replace package body <package_name> is/as procedure <procedure_name>(parameter <mode> datatype,...); is/as begin executable section; end <procedure_name>; . . . function <fun_name>(parameter <mode> datatype,....) return datatype; is/as begin
Page 47
Using the package elements: syntax: sql>>exec package_name.element_name; ex1_specification: create or replace package new_pack as procedure p1(a in number,b in number,c out number); end; / ex1_body: create or replace package body new_pack as procedure p1(a in number,b in number,c out number) as begin c:=a+b; dbms_output.put_line(c); end p1; end new_pack; / sql>> declare a number:=&a; b number:=&b;
Page 48
ex2_Creating package specification: BASHA>>create or replace package cust_sal as procedure find_sal(c_id customers.id%type); end cust_sal; / ex2_Creating package body: BASHA>>create or replace package body cust_sal as procedure find_sal(c_id customers.id%type) is c_sal customers.salary%type; begin select salary into c_sal from customers where id=c_id; dbms_output.put_line('salary is'||c_sal); end find_sal; end cust_sal; / sql>> declare code customers.id%type:=&id; begin cust_sal.find_sal(code); end; / sql>>exec cust_sal.find_sal(2); sql>>exec cust_sal.find_sal(1); create or replace package e_package as
Page 49
Page 50
sql>>create or replace package body emp_sal as procedure find_sal(empno emp.empno%type) is e_sal emp.sal%type; begin select sal into e_sal from emp where empno=empno; dbms_output.put_line('sal is '||e_sal); end find_sal; end emp_sal; / *********** AUTONOMOUS TRANSACTIONS ************** --> When we call a procedure with in a procedure The procedure which is calling will be treated as called procedure and the procedure called by the procedure is called as calling procedure. if the calling procedure contains TCL(commit,rollback) those will be affected to the called procedure also. in order to overcome this we have autonomous transaction option PRAGMA autonomous_transaction; is used to have autonomous transactions ex: create or replace procedure add_emp as pragma autonomous_transaction; begin insert into emp(empno,ename) values(101,50);
Page 51
Database Triggers: Fires when ever a data event (such as DML) or system event(such as logon or shutdown) occurs on a schema or database. Application trigger will be of oracle forms related. GUIDLINES FOR DESIGNING TRIGGERS --> Design triggers to -> To perform related actions -> Centralized global operation CREATING DML TRIGGERS A triggering statement contains:
Page 52
Ex:
/row level -> 14 times = 14 rows modified update emp set sal=sal+200; \Statement Level -> only once for stmt
Syntax To create a trigger: create or replace trigger <trigger_name> timing event1[or event2 or event3] on <tablename> trigger_body Ex: create or replace trigger intrig before insert on emp for each row begin dbms_output.put_line('While inserting before'); end intrig; / create or replace trigger deltrig before delete on emp for each row begin dbms_output.put_line('While deleting before'); end deltrig;
Page 53
Creating a Single Trigger On multiple Events: create or replace trigger trig12 before insert or delete or update on emp begin if deleting then dbms_output.put_line('While Deleting'); elsif inserting then dbms_output.put_line('While Inserting'); elsif updating then dbms_output.put_line('While updating'); end if; end; / Creating DML row trigger: create or replace trigger <trig_name> timing event1 [or event2 or event3] on table [refrencing old as old/new as new for each row when condition] trigger body Column Qualifiers: OLD: It captures the old value of a datafield. NEW: It records the new values of a datafield.
Page 54
|---------
|------
>> create or replace trigger trig1 before insert on emp for each row begin insert into empbkp values(:new.empno); end; / >> select *From empbkp;
Page 55