Sei sulla pagina 1di 13

Merge : Usage : We can use MERGE command to perform INSERT and UPDATE operation into a single table in single

command. It takes the values from source table and checks whether the values are existing in the destination table according to the condition we have given. If the condition is satisfied, the merge command will update the values into destination table. Otherwise it will insert values into destination table. We can use this MERGE command to simplify operations in which many rows are inserted and updated from a single source. Ex1:We have two tables. One is emp_details and another one is emp_temp. We need to populate the data from emp_temp table into emp_details table with the following conditions. 1. If the employee number is existing in emp_details table, we need to update the remaining values into emp_details table. 2. Otherwise we need to insert values into emp_details table. Suppose both table have 3 columns (emp_no,emp_name,emp_dob). Merge into emp_details T1 Using (select emp_no, emp_name, emp_dob from emp_temp) T2 On (T1.emp_no = T2.emp_no) When matched then Update set emp_name = T2.emp_name, emp_dob = T2.emp_dob when not matched then insert values (T2.emp_no,T2.emp_name,T2.emp_dob); MULTIPLE INSERTS Usage: We can perform multiple inserts in a single command. We can perform all the multiple inserts unconditionally. We can specify conditions using WHEN clause. 1. If we need to check all the conditions, we can use the ALL clause. 2. If we need to check the condition till any one is satisfied, we can use the FIRST clause. 3. If all the WHEN conditions are not satisfied, we can use ELSE clause to do some process. We can use this command in the following situations. 1. Each row in a source table will be populated as more than one row in a destination table. 2. Each row in a source table will be populated into more than one destination table. Ex1 : We have two tables (emp_loan & emp_loan_det). Emp_loan table has three columns (empid,loan1,loan2) and emp_loan_det table has two columns (empid,loan).we need to populate each row in emp_loan table into emp_loan_det table. But empid & loan1 as one row and empid & loan2 as another row. insert all into emp_loan_det values (empid,loan1) into emp_loan_det values (empid,loan2) select empid,loan1,loan2 from emp_loan; #Here emp_loan table contains 3 columns . Above example will populates this 3 columns data into emp_loan_det table like

Advance PL/SQL Concepts

Hanuman Varaprasad . K

emp_loan -----------------EMPID LOAN1 LOAN2 10025 Ln001 Hl5662 10024 Ln011 Hl5602 10027 Ln598 Hl5655 emp_loan_det EMPID LOAN 10025 Ln001 10024 Ln011 10027 Ln598 10025 Hl5662 10024 Hl5602 10027 Hl5655 Ex2: If loan1 column in emp_loan table is not null, we need to populate empid & loan1 columns into emp_loan_det table. Otherwise we wont populate it. We need to apply the same condition for loan2 column also. If the both columns (loan1 and loan2) are null, we need to insert empid with loan amount as zero into emp_loan_det. insert all when loan1 is not null then into emp_loan_det values (empid,loan1) when loan2 is not null then into emp_loan_det values (empid,loan2) else into emp_loan_det values (empid,0) select empid,loan1,loan2 from emp_loan; # He same thing will happens here but instread of one table data will spilt into two tables Ex3: If loan1 column in emp_loan table is not null, we need to populate empid & loan1 columns into emp_loan_det table. Otherwise, if loan2 column is not null, we need to populate empid & loan2 columns into emp_loan_det table. Otherwise , we dont have to populate anything. insert first when loan1 is not null then into emp_loan_det values (empid,loan1) when loan2 is not null then into emp_loan_det values (empid,loan2) select empid,loan1,loan2 from emp_loan; Ex4 :We have three tables (emp_deposit, emp_dep1, emp_dep2). Emp_deposit has three columns (empid, deposit1,deposit2), emp_dep1 has two columns (empid,dep1) & emp_det2 has two columns (empid ,dep2). Values of empid and deposit1 columns in emp_deposit table are populated into emp_dep1 table. Values of empid and deposit2 columns in emp_deposit are populated into emp_dep2 table. insert all into emp_dep1 values (empid,deposit1) into emp_dep2 values (empid,deposit2) select empid,deposit1,deposit2 from emp_deposit; DYNAMIC SQL - Using EXECUTE IMMEDIATE Statement

Advance PL/SQL Concepts

Hanuman Varaprasad . K

Usage : We need Dynamic SQL in the following situations. 1. To execute a SQL data definition statement, data control statement and session control statement in PL/SQL. 2. To choose our schema object at run time. 3. To build our program with different search conditions of DML operations EXECUTE IMMEDIATE statement prepares and immediately executes a dynamic SQL statement or PL/SQL block. Restrictions 1. We cann't use for multi-row queries. 2. Dynamic SQL does not support PL/SQL-specific types (booleans or index-by tables). Only exception is PL/SQL record can appear in INTO clause. 3. We cann't use the bind_variables to pass the name of the schema objects. Ex1:Create a emp table with two fields (empid & empname) begin EXECUTE IMMEDIATE 'CREATE TABLE emp (empid NUMBER,empname VARCHAR2(30))'; end; Ex2: Insert a row in a emp table with values (1001,'Name1001'). declare sql_stmt VARCHAR2(100); emp_id NUMBER := 1001; emp_name VARCHAR2(30) := 'Name1001'; begin sql_stmt := 'INSERT INTO emp VALUES (:1,:2)'; EXECUTE IMMEDIATE sql_stmt USING emp_id,emp_name; end; Ex3: Update the value of empname as 'Name_1001' for the empid 1001 in emp table declare emp_name VARCHAR2(30) := 'Name_1001'; begin EXECUTE IMMEDIATE 'UPDATE emp SET empname = :1 WHERE empid = 1001' USING emp_name; end; Ex4: Delete a row in a emp table with the value of empid is 1001 begin EXECUTE IMMEDIATE 'DELETE emp WHERE empid = 1001'; end; Ex5:Querying the value of empname from emp table for the empid 1001 declare sql_stmt varchar2(100); emp_id number := 1001; emp_name varchar2(30); begin sql_stmt := 'select empname from emp where empid = :1';

Advance PL/SQL Concepts

Hanuman Varaprasad . K

EXECUTE IMMEDIATE sql_stmt INTO emp_name USING emp_id; end; Ex6:Using RETURNING clause in DML operations declare sql_stmt varchar2(100); emp_id number := 1001; emp_name varchar2(30); begin sql_stmt := 'delete emp where empid = :1 RETURNING empname INTO :2'; EXECUTE IMMEDIATE sql_stmt USING emp_id RETURNING INTO emp_name; end; Ex7: Calling stored program 'cal_salary' from PL/SQL block declare sql_stmt varchar2(100); begin sql_stmt := 'begin cal_salary; end;'; EXECUTE IMMEDIATE sql_stmt; end; Ex8 :Using session control statement in dynamic SQL begin EXECUTE IMMEDIATE 'alter session set nls_date_format=''DD-MM-YYYY'''; end; DYNAMIC SQL - Using OPEN-FOR, FETCH & CLOSE Usage : we can execute a Multi-row query in Dynamic SQL we can use records, objects & collections in Dynamic SQL OPEN-FOR : Execute a query, identifies the result set, position the cursor in the first row of the result set & zeroes the row-processed count kept by %ROWCOUNT. FETCH : Return a row from the result set, assign the values to corresponding variables, increment the row-processed count kept by %ROWCOUNT & position the cursor to the next row of the result set. CLOSE : Disable the cursor variable. Syntax: OPEN cursor_variable FOR dynamic_string USING bind_arguments FETCH cursor_variable INTO define_variables CLOSE cursor_variable Ex1: We have emp table with three columns (empid,empname,empcity).we need to print empid & empname who have the native place is 'CHENNAI'. declare TYPE cur_type IS REF CURSOR; cur_var cur_type; rec_var emp%ROWTYPE; sql_stmt varchar2(100); emp_city varchar2(10) := 'CHENNAI'; begin sql_stmt := 'select * from emp where empcity = :1'; OPEN cur_var FOR sql_stmt USING emp_city;

Advance PL/SQL Concepts

Hanuman Varaprasad . K

loop FETCH cur_var INTO rec_var; EXIT WHEN cur_var%NOTFOUND; dbms_output.put_line(rec_var.empid); end loop; CLOSE cur_var; end; BULK DYNAMIC SQL usage: Bulk dynamic SQL improves the perfomance by minimizing the context switches between the PL/SQL and SQL Engines Entire collection is passed to SQL engines or returned from SQL engines EXECUTE IMMEDIATE, FETCH & FORALL commands support dynamic bulk bind syntax: 1. EXECUTE IMMEDIATE cursor_variable BULK COLLECT INTO define_variables USING bind_arguments [RETURNING | RETURN] BULK COLLECT INTO bind_arguments 2. FETCH cursor_variable BULK COLLECT INTO define_variables 3. FORALL index IN lower_bound .. upper_bound statement; we have a emp table with three columns (empid, empname & empsalary). We need to get all the values of empsalary column. declare TYPE sal_type IS TABLE OF NUMBER; sal_var sal_type; begin EXECUTE IMMEDIATE 'select empsalary from emp' BULK COLLECT INTO sal_var; for i in sal_var.first .. sal_var.last loop dbms_output.put_line(' val '||sal_var(i)); end loop; end; Ex2: we have a emp table with three columns (empid, empname & empsalary). We need to get all the values of empid and empname columns. declare TYPE cur_type IS REF CURSOR; TYPE id_type IS TABLE OF NUMBER; TYPE name_type IS TABLE OF VARCHAR2(30); cur_var cur_type; id_var id_type; name_var name_type; begin OPEN cur_var FOR 'select empid,empname from emp'; FETCH cur_var BULK COLLECT INTO id_var,name_var; CLOSE cur_var;

Advance PL/SQL Concepts

Hanuman Varaprasad . K

for i in id_var.first .. id_var.last loop dbms_output.put_line(' id '||id_var(i)||' name '||name_var(i)); end loop; end; Ex3: we have a emp table with three columns (empid, empname & empsalary). We need to update all the values of empsalary to 30000 and return the effected empnames. declare TYPE id_type IS TABLE OF NUMBER; TYPE name_type IS TABLE OF VARCHAR2(30); id_var id_type; name_var name_type; begin EXECUTE IMMEDIATE 'select empid from emp' BULK COLLECT INTO id_var; FORALL i in id_var.first .. id_var.last EXECUTE IMMEDIATE 'update emp set empsalary = 30000 where empid = :1 returning empname into : 2' USING id_var(i) RETURNING BULK COLLECT INTO name_var; for i in name_var.first .. name_var.last loop dbms_output.put_line(' name '||name_var(i)); end loop; end; FOR ALL Statement Usage : 1. It minimize the number of context switches between the PL/SQL and SQL Engines. 2. Entire collections are passed to SQL engines or back from SQL engines. 3. We must use INSERT or DELETE or UPDATE statement in FORALL statement.It must reference at least one collection. 4. It can manipulate object tables. 5. We can use %BULK_ROWCOUNT attribute.The number of rows processed by the ith execution is stored in %BULK_ROWCOUNT(i). 6. We can use FORALL statement only in server-side program. 7. Collection subscript can not be expression. 8. Syntax: FORALL index IN lower_bound .. Upper_bound sql_statement; Ex1: We insert values from collection into emp table using FORALL statement.The emp table has two fields (empno,empname). DECLARE type eno_type is table of emp.empno%TYPE; type enm_type is table of emp.empname%TYPE; eno_var eno_type; enm_var enm_type; BEGIN ---fill values into the collections eno_var & enm_var

Advance PL/SQL Concepts

Hanuman Varaprasad . K

FORALL i IN eno_var.first .. eno_var.last INSERT INTO emp VALUES (eno_var(i).enm_var(i)); END; BULK COLLECT clause usage : 1. It minimize the number of context switches between the PL/SQL and SQL Engines. 2. We can use it in SELECT INTO, FETCH INTO & RETURNING INTO clauses. 3. we can limit the number of rows fetched from the database using LIMIT clause in FETCH statement. The value can be literal , variable or expression. But, It should be a positive number. 4. We can use the BULK COLLECT clause in the RETURNING INTO clause with INSERT, DELETE or UPDATE statement. 5. We can use the BULK COLLECT clause only in server-side programs. 6. All targets in a BULK COLLECT INTO clause must be collections. 7. We cannot bulk-fetch from a cursor into a collection of records. 8. Composite targets (such as objects) cannot be used in the RETURNING INTO clause. 9. We can combine the BULK COLLECT clause with a FORALL statement. 10. Ex1: We query values from the table emp which has two columns (empno & empname) using BULK COLLECT. declare TYPE empno_type IS TABLE OF empno.emp%TYPE; TYPE empname_type IS TABLE OF empname.emp%TYPE; empno_var empno_type; empname_var empname_type; begin SELECT empno,empname BULK COLLECT INTO empno_var,empname_var FROM EMP; end; Ex2: We query values from the table emp which has two columns (empno & empname) using BULK COLLECT. declare TYPE empno_type IS TABLE OF empno.emp%TYPE; TYPE empname_type IS TABLE OF empname.emp%TYPE; empno_var empno_type; empname_var empname_type; CURSOR C1 is select empno, empname from emp; begin OPEN C1; FETCH C1 BULK COLLECT INTO empno_var,empname_var; CLOSE C1; end; Ex3:We query values from the table emp which has two columns (empno & empname) using BULK COLLECT. Each time we need to fetch 25 rows. declare TYPE empno_type IS TABLE OF empno.emp%TYPE; empno_var empno_type; CURSOR C1 is select empno from emp; lim_rows number := 10; begin

Advance PL/SQL Concepts

Hanuman Varaprasad . K

OPEN C1; LOOP; FETCH C1 BULK COLLECT INTO empno_var LIMIT lim_rows; EXIT WHEN C1%NOTFOUND; END LOOP; CLOSE C1; end; Using BULK COLLECT with RETURNUNG INTO clause. declare TYPE empno_type IS TABLE OF empno.emp%TYPE; empno_var empno_type; begin DELETE emp WHERE empcd = 401 RETURNING empno BULK COLLECT INTO empno_var; end; TEMPORARY TABLES Usage: 1. Oracle does not allocate space when temporary table is created. Space will be allocated dynamically for the table as rows are inserted. 2. We can hold the values of the table for the duration of our sesson. 3. We can hold the values of the table for the duration of our transaction. 4. Syntax: Ex1:Create a temporary table emp_temp with two columns (eno,ename) to hold the values for the duration of our transaction. create global temporary table emp_temp (eno number,ename varchar2(30)) on commit delete rows; ex2: Create a temporary table emp_temp with two columns (eno,ename) to hold the values for the duration of our session. create global temporary table emp_temp (empno number,empname varchar2(30)) on commit preserve rows; LIST PARTITION Usage :We can choose the partition based on values CREATE TABLE TABLE_NAME (...) PARTITION BY LIST (COLUMN_NAME) (PARTITION PARTITION_NAME VALUES(value1,value2), PARTITION PARTITION_NAME VALUES(value3,value4,value5)); Ex:Create a table emp with three columns(eno,ename,edes).First partition should has the values 'Consultant','Associate aconsultant' and 'Trainee'. Second partition should has the values 'Project Leader' & 'Project Manager'. CREATE TABLE EMP (ENO NUMBER,ENAME VARCHAR2(30),EDES VARCHAR2(30)) PARTITION BY LIST (EDES) (PARTITION PART1 VALUES ('Consultant','Associate consultant','Trainee'), PARTITION PART2 VALUES ('Project Leader','Project Manager')); EXTERNAL TABLES Usage :

Advance PL/SQL Concepts

Hanuman Varaprasad . K

1. External table is used to access external files. 2. Data is not stored the database and We don't need to upload the data into database. 3. When we query the table, Oracle reads the external table and return the results. 4. It is benefit for data warehouses and large databases. 5. We can not do insert or delete or update operation in external table. 6. We can not index external tables. 7. Ex1:External file testtext.lst contains two values(eno,ename). We need to access this data using external table. Records are terminated by newline and fields are terminated by "~". 1. we must define a directory object to point to the external file location. create directory directory_name as 'location'; 2. we need to give READ & WRITE permision to the schema. grant read on directory directory_name to schema_name; grant write on directory directory_name to schema_name; 3. creating external table. create table table_name (eno varchar2(10),ename varchar2(30)) organization external (type ORACLE_LOADER, default directory directory_name access parameters (records delimited by newline fields terminated by "~" (eno CHAR(10), ename CHAR(30))) location ('testtext.lst') ); 4. we can query values from table. select eno,ename from table_name; CASE statement Usage : 1. CASE statement evaluates a condition and performs an action for each case. 2. CASE expression evaluates a condition and returns a values for each case. 3. The selector followed by one or more WHEN clauses, which are checked sequentially. The value of selector determines which clause is executed.If the first value of WHEN clause is matched with selector, It won't evaluate the other WHEN clasues. 4. The value of selector is not one of the choices covered by a WHEN clauses, the ELSE clause is executed. 5. If you omit the ELSE clause, PL/SQL adds the folowing implicit ELSE clause ELSE RAISE CASE_NOT_FOUND; Syntax: CASE Statement: CASE selector WHEN expression1 THEN result1; WHEN expression2 THEN result2; WHEN expression3 THEN result3; ELSE result4 END CASE;

Advance PL/SQL Concepts

Hanuman Varaprasad . K

CASE Expression: CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 WHEN expression3 THEN result3 ELSE result4 END; Ex1: Using CASE statement. declare cnt NUMBER := 10; begin CASE cnt WHEN 5 THEN DBMS_OUTPUT.PUT_LINE('Test_five'); WHEN 10 THEN DBMS_OUTPUT.PUT_LINE('Test_ten'); WHEN 15 THEN DBMS_OUTPUT.PUT_LINE('Test_fifteen'); ELSE DBMS_OUTPUT.PUT_LINE('Test_others'); END CASE; end; ex2: Using CASE statement in another form. declare str1 STRING(10) := 'SECOND'; begin CASE WHEN str1 = 'FIRST' THEN DBMS_OUTPUT.PUT_LINE('Test_first'); WHEN str1 = 'SECOND' THEN DBMS_OUTPUT.PUT_LINE('Test_second'); WHEN str1 = 'THREE' THEN DBMS_OUTPUT.PUT_LINE('Test_three'); ELSE DBMS_OUTPUT.PUT_LINE('Test_others'); END CASE; end; Ex3: Using CASE expression. declare ass_val number; chk_val varchar2(10) := 'first'; begin ass_val := CASE chk_val WHEN 'first' THEN 1 WHEN 'second' THEN 2 ELSE 3 END; dbms_output.put_line(' value '||ass_val); end; CURSOR EXPRESSION Uasge :1. A cursor expression returns a nested cursor.

Advance PL/SQL Concepts

Hanuman Varaprasad . K

2. Each row in the result set can contain values as usual and cursors produced by subqueries involving the other values in the row. 3. A single query can return a large set of related values retrieved from multiple tables. 4. PL/SQL supports queries with cursor expressions as part of cursor declarations. 5. We can also use cursor expression in dynamic SQL queries. 6. The nested cursor is implicitly opened when the containing row is fetched from the parrent cursor. 7. The nested cursor is closed when the parent cursor is closed. We can not use a cursor expression with an implicit cursor. Syntax: CURSOR ( subquery ) We fetch a location and a cursor from which we can fetch all the departments in that location. declare type ref_type is ref cursor; dep_ref ref_type; loc_val string(30); dep_val string(30); cursor c1 is select locnm , cursor(select depnm from dept_tab dep where loc.locno = dep.locno) dep_nm from loc_tab loc; begin open c1; loop fetch c1 into loc_val,dep_ref; exit when c1%NOTFOUND; loop fetch dep_ref into dep_val; exit when dep_ref%NOTFOUND; dbms_output.put_line(' loc '||loc_val||' dept '||dep_val); end loop; end loop; end; MULTILEVEL COLLECTIONS Usage :1. We can create collections whose elements are collection. 2. We can create nested table of varrays, a varray of varrays, varray of nested tables and so on. 3. Ex1: declare type nes_type is table of number; type var_type is varray(10) of nes_type; nes_var nes_type; var_var var_type; nes_var1 nes_type; var_num number; begin nes_var := nes_type(10,20,30); var_var := var_type(nes_var,nes_type(11,21,31),nes_type(12,22,32)); var_var(3).delete(3); nes_var1 := var_var(3); var_var(2)(3) := 41; var_num := var_var(2)(3); for j in var_var.first .. var_var.last

Advance PL/SQL Concepts

Hanuman Varaprasad . K

loop for i in var_var(j).first .. var_var(j).last loop dbms_output.put_line(var_var(j)(i)); end loop; end loop; end; INHERITANCE Usage : 1. PL/SQL support simple inheritance. You can define subtypes of object types. 2. Subtypes contain all the attributes and methods of the parent type. 3. Subtypes can contain additional methods and attributes. 4. Subtypes can override methods from the supertype. Ex1: CREATE TYPE bas_ty AS OBJECT (eno number, ename varchar2(30)) NOT FINAL; CREATE TYPE chi_ty UNDER bas_ty (eaddr varchar2(30)); declare ty_var chi_ty; begin ty_var := chi_ty(10,'enmae10','eaddr10'); dbms_output.put_line(' no '||ty_var.eno||' name '||ty_var.ename||' addr '||ty_var.eaddr); end; TABLE FUNCTIONS Usage: 1. Table function is a function that produce a collection of rows. 2. It can be queried like a phycial database table. 3. It can take a collection of rows as input. 4. Execution of a table function can be parallelized and returened rows can be streamed directly to next process without intermediate staging. 5. It can be pipelined. It is iteratiavely returned as they are produced instead of in a batch. Ex1: Using Table Function : create type nt_obj as object (eno number); create type type_nt as table of nt_obj; create function fun_tab(nt_lim number) return type_nt as nt_var type_nt := type_nt(NULL); begin nt_var.extend(nt_lim-1,1); for i in 1 .. nt_lim loop nt_var(i) := nt_obj(i+1000); end loop; return nt_var;

Advance PL/SQL Concepts

Hanuman Varaprasad . K

end; select b.eno from table(fun_tab(10)) b; Ex2: Using PIPELINED table function : create or replace function fun_pip (num1 number,num2 number) return type_nt pipelined is var_obj nt_obj; begin var_obj := nt_obj(num1); pipe row(var_obj); var_obj := nt_obj(num2); pipe row(var_obj); return; end; select a.eno from table(fun_pip(1001,1002)) a;

Advance PL/SQL Concepts

Hanuman Varaprasad . K

Potrebbero piacerti anche