Best Practices in PL/SQL: Karthikeyan M
Best Practices in PL/SQL: Karthikeyan M
Karthikeyan M http://karthikeyanmect.blogspot.com
Will give solution (some how) Time taken and resource consumed ? Use optimal resource Provides quicker solution
Best code
Modularized Design
Bad design
Dump your logic in a single procedure Having lots of selects inserts updates and deletes.etc Break your logic into small blocks Grouping related logic as a single block or program
.
Modularize
Modularize will
reduce complexity make your tasks manageable make your resulting code maintainable For each major functionality With repeated DML as procedure With repeated select as functions
.
Use Packages
Naming convention
Easy to understand Easy for maintain and change Local variable l_var_name Procedure parameter p_var_name Global variable g_var_name
.
as select d_no into an_document_number from task; begin null; end; end;
Avoid SQL !
Drag the performance down Difficult to maintain Selects inside functions DMLs inside procedures And call these inside your business logic
Avoid repeating the SQL in different places Hard parsing will be avoided So spend more time in design Identify at the time of designing rather than coding
Exception handling
Error handling Error logging Log as more a data as possible (debugging) Date of occurrence Error number , name Program name and program dataetc
.
Normally
BULK COLLECT performs bulk bind of results from SQL select statement
CREATE OR REPLACE FUNCTION get_a_mess_o_emps (deptno_in IN dept.depno%TYPE) RETURN emplist_t IS emplist emplist_t := emplist_t(); TYPE numTab IS TABLE OF NUMBER; TYPE charTab IS TABLE OF VARCHAR2(12); TYPE dateTab IS TABLE OF DATE; enos numTab; names charTab; hdates dateTab; BEGIN SELECT empno, ename, hiredate BULK COLLECT INTO enos, names, hdates FROM emp WHERE deptno = deptno_in; emplist.EXTEND(enos.COUNT); FOR i IN enos.FIRST..enos.LAST LOOP emplist(i) := emp_t(enos(i), names(i), hiredates(i)); END LOOP; RETURN emplist; END;
Used to reduce the context switching between SQL and PL/SQL engine
.
Conventional Bind
Oracle server
PL/SQL Runtime Engine
PL/SQL block
SQL Engine
FOR aDept IN deptlist.FIRST.. deptlist.LAST LOOP DELETE emp WHERE deptno = deptlist(aDept); END LOOP;
SQL Engine
Points to remember
Take more time in designing Follow coding standard Avoid hard coding Avoid writing more SQL Write tiny chunk of code Dont repeat anything
Books/ Materials
Beginning Oracle Programming Sean Dillon, Christopher Beck , Thomas Kyte http://asktom.oracle.com http://www.toadworld.com/sf Code Complete by Steve McConnell