Replace trivial computation with PL/SQL Function?

I have several queries that are computing integral day differences based on an Oracle date field -- for example, something along the line of:
select
Customer
, trunc(current_date) - trunc(payment_date)
from
( select 'Fred' Customer, to_date('2009-06-01 07:05:00', 'yyyy-mm-dd hh24:mi:ss') as payment_date from dual union all
select 'Barney', to_date('2009-07-01 15:15:15', 'yyyy-mm-dd hh24:mi:ss') from dual
-- Customer Account_Age
-- Fred 49
-- Barney 19
I have a developer that is now advising that we use a PL/SQL user defined function rather than the difference of these TRUNC functions. That goes against the grain for me. In the MS SQL Server Transact SQL forums I would almost never recommend replacing a trivial expression with a user defined function because the UDF gets called for each row returned by the query and adds overhead to the query.
Does the same kind of logic apply to Oracle UDFs? Is it a good idea to replace trivial calculations such as this with UDFs?
Kent Waldrop

Kent Waldrop wrote:
Would you use the function instead of the inline calculation if it were not a large data warehouse but the target number of rows was in the millions?That would depend...
- What are the odds that the business will change the definition of this calculation? The more likely it is to change, the bigger the benefit to centralizing it.
- How many places is the calculation repeated today? Is that likely to increase over time? The more it is repeated, the bigger the benefit to having one standard place for it.
- Is this going to be a calculation that gets reimplemented in a variety of reporting tools, in SQL, in applications, etc? Again, this goes to the size of the benefit.
- What are you doing with the results of the SELECT statement? If you're using it in an INSERT ... SELECT, you're more likely to notice the performance overhead than if you've got a FOR loop that is doing row-by-row processing.
- How critical is performance of this query? If you're processing millions of rows but that is happening in the dead of night, perhaps adding a few minutes to the run is well worth the improved maintainability.
Different people, working on different systems, will weight these factors differently and come to different conclusions. Either solution is defensible under the right circumstances and there's a large middle ground where both are reasonable to most people. Steven Feuerstein, one of the most well respected PL/SQL gurus, would push strongly for a function in almost all cases. Most of the commentators here would tend to lean toward the performance benefits of putting the calculation in SQL.
Justin

Similar Messages

  • Interactive Report with PL/SQL Function Source

    Is it possible to create interactive report with PL/SQL function source returing a query? If not, has anyone done any work to simulate the interactive reporting feature for a normal report using API?

    I haven't tried that before but you could:
    1. create a collection from your result set returned by a dynamic query,
    2. create a view on that collection,
    3. use the view in your interactive report.
    The usability of this proposal depends from a question how "dynamic" your query is - does it always have the same number of columns or not.
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.opal-consulting.de/training
    http://apex.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • Burned CDs will not sync to my ipod. I just replaced my computer with a different computer, unauathorizeed all previous computers, authorized the one i am now using, but only purchase content will transfer to my ipod.

    Burned CDs will not sync to my ipod. I just replaced my computer with a different computer, unauathorizeed all previous computers, authorized the one i am now using, but only purchase content will transfer to my ipod.

    Hi ballen13!
    I have an article here for you that may be able to address your question and provide some insight into this issue:
    Some songs in iTunes won't copy to iPod
    http://support.apple.com/kb/TS1420
    Take care, and thanks for visiting the Apple Support Communities.
    -Braden

  • Problem with PL/SQL Function Body

    Hi,
    I'm getting the following error, when i run the report.
    I'm trying to fetch a year value from a table based on a parameter value ":P33_YEAR"
    ORA-01403: no data found
    Error ERR-1904 Unable to compute item default: type = Function Body computation_type= DECLARE FY VARCHAR2(6); BEGIN SELECT DISTINCT YEAR1 INTO FY FROM REP WHERE YEAR = TRIM(:P33_YEAR);
    RETURN FY; END;.
    I have written this code in a PL/SQL Function Body for a Hidden item.
    Please let me know whats wrong with this code?
    Thanks
    CK
    Message was edited by:
    user536304

    Your code is in a default value for an item, right?
    You need to make sure :P33_YEAR is not null and handle the error in the PL/SQL if it is.
    How is P33_YEAR populated? do you pass it in? check to see if it is making it there..
    Message was edited by:
    Bill Carlisle

  • Populating item with pl/sql function body

    Hi,
    I want to populate a "Display as text (saves state)" item with the difference of 2 other items.
    The source of my item is:
    - Only when current...
    - PL/SQL Function body
    - Source expression:
    DECLARE
    v_diff NUMBER;
    BEGIN
    v_diff := :P1_AUFWAND_TOTAL - :P1_AUFWAND_BERECHNET;
    return v_diff;
    END;
    Now I get this error:
    ORA-06502: PL/SQL: numerischer oder Wertefehler: Fehler beim Konvertieren von Zeichen zu Zahl
         Error      ERR-1904 Unable to compute item default: type = Function Body...
    I tried to track down the problem with to_number conversion:
    v_diff := to_number(':P1_AUFWAND_BERECHNET'); or
    v_diff := to_number(':P1_AUFWAND_BERECHNET', '999G999D00');
    What's wrong here? It feels like I'm making a simple mistake...
    Thanks for any help,
    Roger

    Hi Denes,
    Thanks for your help. You were right, item :p1_aufwand_berechnet was not a number.
    I created the problem myself by setting the format to:
    return TO_CHAR(v_aufwand,'999G999G999G999G990D00');
    Now the dilemma is that I want to calculate the numbers, but at the end I want a nice format to display them. This obviously only works with TO_CHAR, see:
    Re: Number format mask of text item is not applied
    Maybe this is to be solved with a seperate process after the calculation, to set the format?
    Cheers,
    Roger

  • Read consistency in query with pl/sql functions

    Not sure if this is a bug or feature, but a query containing a user-defined pl/sql function does not include tables accessed within the pl/sql function in the read consistent view of data, eg
    select myfunc from tableA
    myfunc is a stored function that queries tableB and returns a value
    If a change to tableB is committed in another session during fetch phase of select statement, then fetched rows reflect the changes. The database does not recognise tables accessed in the plsql function as being part of the query.
    This happens in 7.3.4 and 8.1.6. Don't have 9i so can't tell.
    Anyone know if this is a bug or feature?
    Aside: you can also drop the plsql function whilst the fetch is running. It will kill the fetch. No DDL lock taken on the plsql function whilst select is running! Seems wrong.

    I don't know Forms but I know SQL*Plus and Oracle database. Normally PL/SQL running on the database can only access files on the host where the database instance is running even if you start PL/SQL with a SQL*Plus connection from another host.
    PL/SQL runs only the database instance not on the client side even if you start the PL/SQL code from a remote connection with SQL*Plus.

  • The troubles with creating SQL function in Java

    Hi!
    I use Oracle 10g and connect to it from Java application. I need in creating SQL functions from Java code.
    In Java I have:
    Statement stm = null; try{     stm = dbConnection.createStatement();     stm.executeUpdate( query ); }catch(SQLException ex){     throw ex; }finally{     try{ stm.close(); }catch(Exception ex){ stm.close(); } }
    And I'm passing the next SQL function:
    create or replace function get_me return number is
    result number;
    begin
    select 5 into result from dual;
    return result;
    end;
    This code is run successful, but I can't call this funtion, because it has status Invalid
    I'm looked the next error: PLS-00103: Encountered the symbol "" when expecting one of the following: . @ % ; is authid as cluster order using external character deterministic parallel_enable pipelined aggregate
    But I don't understand, What the matter? From Oracle Enterprise Manager I can create this function without problems. So, I wrote the wong Java code. Also, I can't find my error :(
    May be, do u have the some ideas?
    Thank you very much!

    Post the whole pl/sql code please.
    To run PL/SQL from within java you'll need callablestatement.
    [here |http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java] an example : http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java

  • Conditional display of region with PL/SQL function returning SQL query

    Hello,
    ApEx 2.0.
    I use PL/SQL functions that return SQL queries to display the contents of a region.
    How could I conditionally display such region ? If no data is found, the region shouldn't be shown. I tried with "SQL query returns at least one row" but this doesn't seem to work.
    Thanks,
    Matthias

    Hi Matthias,
    Are the regions in question report regions? So your PL/SQL process is returning a SQL query and then populating a report?
    The EXISTS(SQL Query returns at least one row) condition should work, try running the query you are using in the Expression 1 textarea inside SQL*Plus, or SQL developer using the same parameters, and see what gets returned.
    If you are still stuck, can you post the query you are using inside your Expression 1 textarea of the Conditions section and I can take a look at it for you.
    Hope this helps,
    Cj

  • String Substitutions with PL/SQL Function

    Hello, i user APEX 4.2.1.00.08 in Database 11g
    I new in apex and a try to use String Substitutions.
    When I define a String like CONST with static value like '999' in Edit Applications Definition it's work fine.
    But I need to define the same String 'CONST' but with value to return from PL/SQL function like.. Package.function
    It's Possible ??
    Thanks !!

    No, you'll need to use application items instead - or pass the value as parameter to your function.
    Passing parameters like this makes for good practice anyway, since your modules become more testable outside the apex environment, and more robust.

  • How to use "Submit - after computation" with PL/SQL?

    Hi,
    I'm new in APEX
    My scenario: I have a date column that I need to populate automatically (DATE_CREATION = sysdate) when I create a row, probably on "Submit - After Computations and VAlidations" with PL/SQL, how can I do that?
    Thanks for your reply
    Sam Karema

    You should be able to use the PL/SQL APIs to get the current page
    or back page. The portlet runtime record has these APIs
    type portlet_runtime_record is record
    portlet_id - number,
    provider_id - number,
    node_id - number,
    reference_path - varchar2(100),
    language - varchar2(30)
    exec_mode - number,
    back_page_url - varchar2(4098),
    page_url - varchar2(4098),
    page_type - varchar2(200),
    has_title_region - boolean,
    has_border - boolean
    caching_key - varchar2(200),
    caching_level - varchar2(30),
    caching_period - number
    back_page_url
    The URL for the calling page.
    Notes: The value stored in this field is used by portlets to
    redirect users to the calling page (previous page).
    This value can be null if there is no calling URL.
    Datatype: varchar2
    page_url
    The URL of the page that contains the portlet instance that will
    receive the portlet_runtime_record. Current page.
    Datatype: varchar2
    Hope this helps,
    Sue

  • Replaced crashed computer with new one. How do I secure a serial number for my re-installed CS3 program obtained while as a student at Dixie State University with a coupon code of HL1A-003B-L2A0? Trial expires in 7 days.

    My old computer, which had CS3 installed, crashed and I had to replace the computer.  We re-installed the CS3 program on the new computer, and the prompt calls for a serial number, which we do not have.  I obtained the original CS3 while registered as a student at Dixie State University.  The Coupon Code is: HL1A-003B-L2AO.  There are only 7 days remaining on the new trial period.  I e-mailed Adobe requesting a serial number several days ago, but have not received a response.  How do I secure the serial number?  Rollo B.

    Hi.\
    Welcome to the Photoshop user to user forums. Since we are not Adobe employees, we can't fix serial number and activation problems. Only Customer Care can do this.
    Contact Customer Care
    Gene

  • Plugin with PL SQL function returning query

    Hi all,
    I have created plugin using SQL query many times. But can we create a plugin from scratch using PL SQL function returning SQL query? Any ideas or sample.
    Thanks
    Sunil Bhatia

    Hi Scott,
    By this i mean, i have created a region type plugin for integrating jqx Grid into oracle apex. This takes input parameter as SQL statement, and creates jqx grid for me on page. Now my question is, can i do this using PL SQL function returning SQL, because when i try to give return statement, plugin gives error "SQL statement mandatory'. I hope i am clear enough now.
    Thanks
    Sunil Bhatia

  • Could i replace my computer with an ipod touch???

    OK so i have been thinking if i could replace my laptop with my Ipod Touch 5g. It has plenty of apps, like pages, to replace microsoft word programs. Its is ultra portable. And it is sadly faster than my laptop when it comes to internet speeds.  Could it work? I just wonder because it may save money and lots of effort and other things. Thanks

    AnaMusic wrote:
    Philly_Phan wrote:
    Well, you could replace your laptop with a toaster ...
    Sorry... I could read no further...
    I couldn't resist.  I'm in that kind of mood right now!

  • Need help with PL/SQL functions

    Hi,
    Is there a way to compare if a set of elements is present in another set using some function?
    Example: Is it possible to find out if all words present in 'BANQUE SAFRA SA' is present in 'BANQUE JACOB SAFRA (SUISSE) SA' using some function in Oracle 9i?
    Any suggestion would be appreciated.
    Thank you,
    Anushree

    Boneist,
    your solution would giv "false positives":
    SQL> with my_tab as (select 'BANQUE JACOB SAFRA (SUISSE) SA' col1 from dual union all
      2                  select 'BANQUE SAFRA (SUISSE) SB' col1 from dual union all
      3                  select 'BANQUE SAFRA SA' col1 from dual union all
      4                  select 'BANQUE SAFRANE SA' col1 from dual)
      5  -- end of mimicking your data. USE SQL below!
      6  select * from my_tab
      7  where col1 like replace('BANQUE SAFRA SA', ' ', '%');
    COL1
    BANQUE JACOB SAFRA (SUISSE) SA
    BANQUE SAFRA SA
    BANQUE SAFRANE SA  Here is a PL/SQL funcion that does not expect the words in the specific order:
    SQL> DECLARE
      2     FUNCTION strInStr(
      3        a   IN   VARCHAR2,
      4        b   IN   VARCHAR2)
      5        RETURN VARCHAR2
      6     IS
      7        i          PLS_INTEGER;
      8        startpos   PLS_INTEGER;
      9        endpos     PLS_INTEGER;
    10        word       VARCHAR2(4000);
    11     BEGIN
    12        FOR i IN 1 .. LENGTH(a) - LENGTH(REPLACE(a, ' ')) + 1 LOOP
    13           startpos := INSTR(' ' || a, ' ', 1, i);
    14           endpos := INSTR(a || ' ', ' ', 1, i);
    15           word := SUBSTR(a, startpos, endpos - startpos);
    16
    17           IF ' ' || b || ' ' NOT LIKE '% ' || word || ' %' THEN
    18              RETURN 'N';
    19           END IF;
    20        END LOOP;
    21
    22        RETURN 'Y';
    23     END;
    24  BEGIN
    25     DBMS_OUTPUT.put_line(strInStr('BANQUE SAFRA SA', 'BANQUE JACOB SAFRA (SUISSE) SA'));
    26     DBMS_OUTPUT.put_line(strInStr('SAFRA BANQUE SA', 'BANQUE JACOB SAFRA (SUISSE) SA'));
    27     DBMS_OUTPUT.put_line(strInStr('BANQUE SAFRA FRANCE', 'BANQUE JACOB SAFRA (SUISSE) SA'));
    28     DBMS_OUTPUT.put_line(strInStr('QUE SAFRA SA', 'BANQUE JACOB SAFRA (SUISSE) SA'));
    29  END;
    30  /
    Y
    Y
    N
    N

  • Problem with extended SQL functions in RTF Template

    Hello,
    I'm new to BI Publisher and I'm trying to create a new rtf template. I've created my layout and added fields without any problems, but I'm having trouble trying to insert calculations such as add,substract,multiply,divide, etc.
    Here is an example of what I'm trying to do:
    <?xdofx:STAFF_ASMT+100?>
    Where STAFF_ASMT is one of my fields. When I add this function all I get is the actual value from that field returned on the first page, and then on other pages I get the value plus an extra zero.
    So with my example data below I get: 6600 on page 1 and 51830 on page 2. Any ideas on what I'm doing wrong or if it is possible to do what I'm doing? Also, is it possible to add/substract/multiple two or more fields together?
    Something like this: <?xdofx:STAFF_ASMT+GROSS_INV?>
    I was going to add all of these functions to my SQL statement, but I have 30 or so calculations I want to perform in the layout and I don't want to have to write that all out in SQL.
    <ROWSET>
    <ROW>
    <STAFF_ASMT>6600</STAFF_ASMT>
    <GROSS_INV>0</GROSS_INV>
    </ROW>
    <ROW>
    <STAFF_ASMT>5183</STAFF_ASMT>
    <GROSS_INV>0</GROSS_INV>
    </ROW>
    </ROWSET>
    Thanks for your help

    When I tried that I get the following error message when I click the Validate Template option:
    [080609_031631893][][ERROR] [Line 162.184] Incorrect XPath: +
    And when I try to generate a PDF preview I get:
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLT10gR1.invokeNewXSLStylesheet(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLT10gR1.transform(Unknown Source)
         at oracle.apps.xdo.common.xml.XSLTWrapper.transform(Unknown Source)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(Unknown Source)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(Unknown Source)
         at oracle.apps.xdo.template.FOProcessor.createFO(Unknown Source)
         at oracle.apps.xdo.template.FOProcessor.generate(Unknown Source)
         at RTF2PDF.runRTFto(RTF2PDF.java:629)
         at RTF2PDF.runXDO(RTF2PDF.java:439)
         at RTF2PDF.main(RTF2PDF.java:289)
    Caused by: oracle.xdo.parser.v2.XPathException: Error in expression: './/+'.
         at oracle.xdo.parser.v2.XSLProcessor.reportException(XSLProcessor.java:806)
         at oracle.xdo.parser.v2.XSLProcessor.newXSLStylesheet(XSLProcessor.java:571)

Maybe you are looking for