oracle developer programming tips

Upload: archana-das

Post on 08-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Oracle Developer Programming Tips

    1/4

    Displaying Elapsed Time: The difference between two dates

    If you ever need to display the number of hours, minutes and seconds between two events, this will help. This little package can becalled once to record the start time, then later to display the elapsed time since the initial call. It has two modes of displaying thetime, depending on whether the elapsed time is more or less than 10 seconds. When it is less than ten seconds, it displays theseconds down to 0.01 second. This process even corrects for some truncation errors caused by the floating point arithmetic used toextract hours, minutes and seconds.

    The output looks like one of these:

    Elapsed time = 9.25 secondsElapsed time (HH:MI:SS) = 00:02:15

    Call Elapsed_Time as follows:

    PK2.ELAPSED_TIME(T,'start'); -- to initializePK2.ELAPSED_TIME(T); -- to retrieve the formatted text.

    Here is the package:

    CREATE OR REPLACE PACKAGE PK2 ISPROCEDURE ELAPSED_TIME

    (T IN OUT VARCHAR2,MODE1 IN VARCHAR2 DEFAULT NULL);END PK2;.

    /SHOW ERRORS PACKAGE PK2CREATE OR REPLACE PACKAGE BODY PK2 IS--------------------------------------

    START_TIME DATE;START_TIMEN NUMBER;--PROCEDURE ELAPSED_TIME---------------------------------

    (T IN OUT VARCHAR2,MODE1 IN VARCHAR2 DEFAULT NULL) ISET NUMBER; -- Elapsed run timeETN NUMBER; -- Elapsed time to hundredths of seconds

    BEGIN

    IF MODE1 IS NOT NULL THENSTART_TIME := SYSDATE;START_TIMEN := DBMS_UTILITY.GET_TIME;

    ELSEET := SYSDATE - START_TIME + 0.000001;ETN := (DBMS_UTILITY.GET_TIME - START_TIMEN) / 100;IF ETN >= 10 THEN

    T:='Elapsed time (HH:MM:SS) = '||Ltrim(To_char( Trunc(ET*24), '99900'))||':'||Ltrim(To_char(Mod(Trunc(ET*1440),60), '00')) ||':'||Ltrim(To_char(Mod(Trunc(ET*86400),60) ,'00'));

    ELSET:='Elapsed time ='

    ||To_char(ETN,'0.00')||' seconds';END IF;

    END IF;END ELAPSED_TIME;--

    END PK2; -- End of Package Body --.

    /SHOW ERRORS PACKAGE BODY PK2

    Here is a script to test the process:

  • 8/6/2019 Oracle Developer Programming Tips

    2/4

    Set SERVEROUTPUT ON SIZE 20000Declare

    T Varchar2(40);X Date;

    BeginPK2.ELAPSED_TIME(T,'start');For I in 1..100 loop

    X := Sysdate; -- Spend some time loopingEnd loop;PK2.ELAPSED_TIME(T);DBMS_Output.Put_Line(T);

    End;.

    /

    Using SQL Plus

    While I would rather write Forms if given a choice, I often find myself with the task of writing some pretty hairy pl/sql procedures. Sohere are some things I have found to be really helpful in getting the job done.

    1. You can change the working directory where SQL Plus looks for scripts to execute from within SQL Plus. To do this, you use the File-> Open pull-down menu selection to get to the Open File window. Use the features in this window to navigate to the directory youwant to use. Then open a file -- I keep a little one with only several lines in it, named ~a.sql (so it is always first). Once you open afile, the directory you are in becomes the current working directory. You can run any .sql script in the directory simply by typing@NAME where NAME is a file named NAME.SQL.

    If you create a small file to open, make sure its last line is a comment, beginning with two dashes, and ending with no Return at theend. This way when you open the file, SQL Plus will return back to the SQL> prompt.

    2. Use the special SQL Plus copy/paste shortcut to quickly re-execute commands. If you have a command on your SQL Plus windowthat you need to type in again, rather than re-typing it, just do this: Highlight the command using the standard Windows method --Press the left mouse button, and drag the mouse across the text. But before releasing the left button, click the right button. This willcopy and paste the text onto the command line. If you pull the mouse down a line, it will also send a Return, causing SQL Plus toexecute the command. You can use this method repeatedly to copy and paste parts of a line or several lines at once on your screen.

    It is a great aid to working with SQL Plus.

    3. Use a good editor.

    4. In PFE, turn on line numbering -- there is an icon on PFE's toolbar, or you can set preferences to always supply them. (PFE doesnot store line numbers with the file.) With PFE's line numbers and my "no blank lines" rule below, you can find the pl/sql errors easily.

    5. NEVER put blank lines in your script. Always use two dashes as a comment line instead. That way, when the PL/SQL compilergives you a line/column where the error occurs, it corresponds to the number in file you are editing. This works for me because I mostalways create a package or procedure, and the file starts with the "CREATE OR REPLACE PROCEDURE..." line, and ends with 3 lines: aperiod alone in column 1 (terminates SQL Plus edit mode), a slash (to run the script), and the command: SHOW ERRORS PROCEDURE

    XXX

    Synchronizing line numbers is really important when your procedure is hundreds or thousands of lines long.

    6. In SQL Plus, to cut or paste text using the keyboard keys, the standard Windows Ctrl-C and Ctrl-V keys do not work -- you getgarbage when you try to paste. Instead, the alternate Ctrl-Insert to copy and Shift-Insert to paste work great.

  • 8/6/2019 Oracle Developer Programming Tips

    3/4

    7. In a SQL Plus script, if you ever run the script and it ends with the message "Input truncated to nn characters", you need to removethe blank spaces from the last line in the script.

    Explain Plan Tips

    I have provided below a short script that I keep in my SQL Plus directory, named Explain.SQL. Any time I want to view the explainplan sequence for some difficult SQL select, I do the following in a SQL Plus session:

    Type EXPLAIN PLAN FOR and press Enter.Paste all the lines of the select statement from my PFE edit session.Execute the statement -- (just press enter)Type @EXPLAINThe Explain.SQL script below does all the rest. Now I just wish I could find an explanation somewhere that would tell me exactly whatthe Explain Plan output means, step by step.------ Begin EXPLAIN.SQL script -----set echo off set feedback off -- This select interprets the output of an-- EXPLAIN PLAN FOR Select.... statement.-- In order to run Explain Plan, the table Plan_Table must exist in

    -- your schema. If it does not, then run (from SQL Plus) the sql-- script C:\ORAWIN\RDBMS71\ADMIN\utlxplan.sql to create it.---- Each time you run Explain Plan, you should either run this script-- OR be sure to delete everything in Plan_Table. All you need is to-- enter is: delete plan_table;-- Note that this script does this at the end.-- If you don't clear out plan_table, then this script loops. You-- can stop the looping by pressing Ctrl-C.--update plan_table set statement_id='A' where statement_id is null;--Select lpad(' ',2*(level-1))||operation||' '||options||' '||object_name

    ||' '||decode(id,0,'Cost = '||position) "Query Plan"From plan_tableStart with id = 0 and statement_id ='A'connect by prior id = parent_id and statement_id ='A';

    delete plan_table;commit;set feedback onset echo on------ End of EXPLAIN.SQL script -----

    If you don't have UTLXPLAN.SQL, just run this:

    create table PLAN_TABLE ( statement_id varchar2(30),timestamp date, remarks varchar2(80),operation varchar2(30), options varchar2(30),object_node varchar2(128), object_owner varchar2(30),object_name varchar2(30), object_instance numeric,object_type varchar2(30), optimizer varchar2(255),search_columns numeric, id numeric,parent_id numeric, position numeric,other long);

  • 8/6/2019 Oracle Developer Programming Tips

    4/4

    PL/SQL coding

    1. Don't code Exception handlers unless you have a clear and compelling reason to do so. Unless there is a specific problem you are trapping, how can you ever guesswhat problem might occur? By leaving out the exception code and by following my no blank lines rule, the line number returned with the exception error points to theexact place the error occurred.

    2. Don't raise your own exceptions in your procedures. My reasons-- they break the rules of structured programming. When you RAISE , it is just a disguised GOTO

    statement, which forces processing immediately to jump to the end of the procedure.

    To handle a user-created exception, you have to write special code in three places in your procedure: you have to declare it (Pragma exception init...), you have to raise it(GOTO the end), and you have to handle it (Exception when...). It is so much easier and clearer to take care of a special condition in-line in your code, especially forsomeone else trying to read your code.

    To pass back an error condition to a calling procedure, use a parameter -- something like Return_Code. Then the calling procedure can test the Return_Code valueimmediately after the call, making all the code easier to follow. If you use an exception in the caller, it isn't immediately clear to the next person reading your code that thesub procedure can raise such an error. It just confuses the process.