? Regarding 'SQL user-defined function' execution performance ?

Hi All,
I have an user-defined function in SQL which am using in a SQL select statement and i found that the execution time taken by the user-defined function is 9-10 minutes as a result of which my whole query execution time is affected.
How to i improvise the execution time. Should i do some sort of scheduling for executing the user-defined functions only. Am new to the database world. Your early response with a good suggestion would really be appreciated.
Thanks in Advance.

Try to read SQL tuning documents along with TkProf. Then only you will be able to detect the problem.
There is no instant method by which you can solve this problem.
But, you can get idea from this samples.
Tuning:
http://www.dba-oracle.com/art_sql_tune.htm
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:8764517459743
Reading TkProf:
http://www.dbspecialists.com/presentations/use_explain.html
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:920429344869
Regards.
Satyaki De.

Similar Messages

  • SQL User Defined Functions for performing statistical calculations

    Hi!
       I hope you can help.  I just wasn’t sure where to go with this question, so I’m hoping you can at least point me in the right direction.
       I’m writing a SQL Server stored procedure that returns information for a facility-wide scorecard-type report.  The row and columns are going to be displayed in a SQL Server Reporting Services report. 
       Each row of information contains “Current Month” and “Previous Month” numbers and a variance column.  Some rows may compare percentages, others whole numbers, others ratios, depending on the metric they’re measuring.  For each row/metric the company has specified whether they want to see a t-test or a chi-squared statistical test to determine whether or not there was a statistically significant difference between the current month and the previous month. 
       My question is this:  Do you know where I can find a set of already-written user defined functions to perform statistical calculations beyond the basic ones provided in SQL Server 2005?  I’m not using Analysis Services, so what I’m looking for are real SQL User Defined Functions where I can just pass my data to the function and have it return the result within a stored procedure. 
       I’m aware that there may be some third-party statistical packages out there we could purchase, but that’s not what I’m looking for.   And I’m not able to do anything like call Excel’s analysis pack functions from within my stored procedure.   I’ve asked.   They won’t let me do that.   I just need to perform the calculation within the stored procedure and return the result.
       Any suggestions?  Is there a site where people are posting their SQL Server UDF’s to perform statistical functions?  Or are you perhaps aware of something like a free add-in for SQL that will add statistical functions to those available in SQL?   I just don’t want to have to write my own t-test function or my own chi-squared function if someone has already done it.
     Thanks for your help in advance!  Oh, and please let me know if this should have been posted in the TSQL forum instead.  I wasn't entirely sure.
    Karen Grube

    STATS_T_TEST_
    docs.oracle.com/cd/B19306_01/server.102/b14200/functions157.htm 
    STATS_T_TEST_ONE: A one-sample t-test
    STATS_T_TEST_PAIRED: A two-sample, paired t-test (also known as a crossed t-test)
    STATS_T_TEST_INDEP: A t-test of two independent groups with the same variance (pooled variances)
    STATS_T_TEST_INDEPU: A t-test of two independent groups with unequal variance (unpooled variances)

  • Calling PL/SQL user defined functions from ODI Constraints

    Hi All,
    We are trying to call user defined PL/SQL functions from ODI. We are able to call them from ODI's User functions. But when we are trying to call them from ODI Constraints under Models, it is throwing an error 'ORA-00920 invalid relational operator'. Kindly let me know if anyone has faced the same issue and got the resolution for the same. Thanks in Advance.
    Regards,
    Abhishek Sharma

    Hi Ace,
    Thanks for the response, the same error was coming in operator also.
    I am able to call PL?SQL user defined functions from ODI Constraints. We have to first call ODI User functions from the ODI constraints as we cant call PL/SQL function (compiled in database) directly.
    From the ODI User functions, we can then call the PL/SQL functions.
    Please reach out to me if you need further details reg this.

  • How to call Microsoft SQL User defined function??

    I am trying to call Miscrosoft SQL user defined function (not stored procedure) and experience problems. The function -- func_profile_history takes 3 inputs and returns resultSet.
    Please let me know if there is any examples some where. All the examples I found are for stored procedure.
    Thanks....
    Siu
    ************ source *************
    public Vector callSqlFunction(String eidTradcom, String idSku, String endDate, String idUserPost)
    throws TradcomException, RemoteException
    System.out.println("--------------in callSqlFunction--------------1");
    Connection conn = null;
    java.sql.CallableStatement cstmt = null;
    ResultSet rs = null;
    ForecastInfo info = null;
    Vector v = new Vector();
    try{
    conn = TradcomUtils.getConnection();
    String sql = "{call func_profile_history(?,?,?)}";
    System.out.println("--------------in callSqlFunction--------sql="+sql);          
    cstmt = conn.prepareCall(sql);
    System.out.println("--------------in callSqlFunction-------2");                         
    cstmt.setString(1, eidTradcom);
    cstmt.setString(2, idSku);
    cstmt.setString(3, endDate);
    System.out.println("--------------in callSqlFunction-------3");                    
    rs = cstmt.executeQuery();
    System.out.println("--------------in callSqlFunction-------4");                    
    while (rs.next()){
         info = new ForecastInfo ();
         info.setEidTradcom(rs.getString("eid_tradcom"));
         info.setIdSku(rs.getString("id_sku"));                    
         info.setQtOnHand(rs.getDouble("qt_on_hand"));                    
         info.setQtOnHold(rs.getDouble("qt_hold"));
         info.setQtNetOnHand(rs.getDouble("qt_net_on_hand"));
         info.setQtAlloc(rs.getDouble("qt_alloc"));
         info.setQtAvailUnalloc(rs.getDouble("qt_avail_unalloc"));     
         info.setQtPoShip(rs.getDouble("qt_po_ship"));
         info.setQtPoRcvd(rs.getDouble("qt_po_rcvd"));
         info.setQtTransit(rs.getDouble("qt_transit"));
         info.setQtAsn(rs.getDouble("qt_asn"));                    
         info.setQtPo(rs.getDouble("qt_po"));
         info.setQtPoBalance(rs.getDouble("qt_po_balance"));
         info.setQtSoShip(rs.getDouble("qt_so_ship"));     
         info.setQt4Cast(rs.getDouble("qt_4cast"));
         v.addElement(info);
    System.out.println("--------------in callSqlFunction-------5");     
    System.out.println("--------------in callSqlFunction-------v="+v);          
    return v;
    }catch(Exception ex){
    System.out.println("Error in callSqlFunction:"+ ex.getMessage());
    throw CachingManager.getTradcomException(ex, "Error in callSqlFunction");
    }finally{
    try{ if (cstmt != null) cstmt.close(); } catch(Exception ex){}
    try{ if (conn != null) conn.close(); } catch(Exception ex){}
    ********************* error output ***************
    ********************* bef calling callSqlFunction
    --------------in callSqlFunction--------------1
    --------------in callSqlFunction--------sql={call func_profile_history(?,?,?)}
    --------------in callSqlFunction-------2
    --------------in callSqlFunction-------3
    Error in callSqlFunction:The request for procedure 'func_profile_history' failed
    because 'func_profile_history' is a function object. Severity 18, State 1, Proc
    edure 'LAP_DUAL null', Line 4
    ERROR=Error in callSqlFunction...The request for procedure 'func_profile_history
    ' failed because 'func_profile_history' is a function object. Severity 18, State
    1, Procedure 'LAP_DUAL null', Line 4

    well, I tried the preparedStatemnet and it worked. Case closed.

  • Regarding sqlserver user defined functions

    Hi,
      How to write user defined functions dynamically?
    Please help me in any situation

    Hi Bellam,
    You post same question 2 times. Please avoid this practice on Forum, I 
    have merged the same thread  into this thread.
    As other post, dynamic SQL is not allowed in user defined functions (UDF), however, you can execute dynamic SQL store procedure with parameter. A user-defined function takes zero or more input parameters and returns either a scalar value or a table. There
     is different between user-defined stored procedures and
    user-defined function. User-defined functions do not support output parameters.
    For more information, you can review the article about User-Defined Functions(UDF).
    http://technet.microsoft.com/en-us/library/ms191007.aspx
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • Using a SQL user-defined function in Crystal Reports XI

    Post Author: JoannKarp
    CA Forum: Formula
    Is it possible to use a user defined function in SQL and use this in multiple Crystal reports?
    JoannKarp

    SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
      FROM table1
    Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
       CASE WHEN a IS NOT NULL THEN a
            WHEN b IS NOT NULL THEN b
            WHEN c IS NOT NULL THEN c
       END
    But if you use isnull it's a different matter. (But isnull() permits two arguments.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Using User Defined Function is SQL

    Hi
    I did the following test to see how expensive it is to use user defined functions in SQL queries, and found that it is really expensive.
    Calling SQRT in SQL costs less than calling a dummy function that just returns
    the parameter value; this has to do with context switchings, but how can we have
    a decent performance compared to Oracle provided functions?
    Any comments are welcome, specially regarding the performance of UDF in sql
    and for solutions.
    create or replace function f(i in number) return number is
    begin
      return i;
    end;
    declare
      l_start   number;
      l_elapsed number;
      n number;
    begin
      select to_char(sysdate, 'sssssss')
        into l_start
        from dual;
      for i in 1 .. 20 loop
        select max(rownum)
          into n
          from t_tdz12_a0090;
      end loop;
      select to_char(sysdate, 'sssssss') - l_start
        into l_elapsed
        from dual;
      dbms_output.put_line('first: '||l_elapsed);
      select to_char(sysdate, 'sssssss')
        into l_start
        from dual;
      for i in 1 .. 20 loop
        select max(sqrt(rownum))
          into n
          from t_tdz12_a0090;
      end loop;
      select to_char(sysdate, 'sssssss') - l_start
        into l_elapsed
        from dual;
      dbms_output.put_line('second: '||l_elapsed);
      select to_char(sysdate, 'sssssss')
        into l_start
        from dual;
      for i in 1 .. 20 loop
        select max(f(rownum))
          into n
          from t_tdz12_a0090;
      end loop;
      select to_char(sysdate, 'sssssss') - l_start
        into l_elapsed
        from dual;
      dbms_output.put_line('third: '||l_elapsed);
    end;
    Results:
       first: 303
       second: 1051
       third: 1515
    Kind regards
    Taoufik

    I find that inline SQL is bad for performance but
    good to simplify SQL. I keep thinking that it should
    be possible somehow to use a function to improve
    performance but have never seen that happen.inline SQL is only bad for performance if the database design (table structure, indexes etc.) is poor or the way the SQL is written is poor.
    Context switching between SQL and PL/SQL for a User defined function is definitely a way to slow down performance.
    Obviously built-in Oracle functions are going to be quicker than User-defined functions because they are written into the SQL and PL/SQL engines and are optimized for the internals of those engines.
    There are a few things you can do to improve function
    performance, shaving microseconds off execution time.
    Consider using the NOCOPY hints for your parameters
    to use pointers instead of copying values. NOCOPY
    is a hint rather than a directive so it may or may
    not work. Optimize any SQL in the called function.
    Don't do anything in loops that does not have to be
    done inside a loop.Well, yes, but it's even better to keep all processing in SQL where possible and only resort to PL/SQL when absolutely necessary.
    The on-line documentation has suggested that using a
    DETERMINISTIC function can improve performance but I
    have not been able to demonstrate this and there are
    notes in Metalink suggesting that this does not
    happen. My experience is that DETERMINISTIC
    functions always get executed. There's supposed to
    be a feature in 11g that acually caches function
    return values.Deterministic functions will work well if used in conjunction with a function based index. That can improve access times when querying data on the function results.
    You can use DBMS_PROFILER to get run-time statistics
    for each line of your function as it is executed to
    help tune it.Or code it as SQL. ;)

  • User Defined Function VS join - Performance....

    Hi All,
    while linking the mulitple table and getting the values ....which one is the best ?
    Joining or User defined function.....
    single row function
    select a.name , get_salary(empid) from emp a;
    Note : get_salary function will return the salary from salary tables.
    Using joins
    select a.name ,b.salary from emp a, salary b
    where a.empid=b.empid;
    which is the performancewise best ?
    also if you give any related document also fine.
    Thanks in advance.
    Edited by: BASKAR NATARAJAN on Jan 6, 2011 10:09 PM

    Don't use such functions for joins. The function itself has to query the salary table. It will run the query against the salary table separately for each row that it reads from the emp table. You will end up with multiple recursive calls and possibly inconsistency in the output. (Imagine what would happen if the salary table were updated and commited while this query was running -- some rows would have been read with the pre-update values and others with the updated values).
    Specifying the join in the query ensures that a single SQL call is executed and provides read consistency across all the rows it reads. And it is much faster, being one single parse and execute.
    Hemant K Chitale
    http://hemantoracledba.blogspot.com

  • How to Use Sequence Object Inside User-defined Function In SQL Server

    I'm trying to call sequence object inside SQL Server user-defined function. I used 
    Next Value for dbo.mySequence  to call the next value for my sequence created. But I'm getting an error like below.
    "NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns, views, user-defined functions, user-defined aggregates, user-defined table types, sub-queries, common table expressions, or derived tables."
    Is there any standard way to call sequence inside a function?
    I would really appreciate your response.
    Thanks!

    The NEXT
    VALUE FOR function cannot be used for User Defined function. It's one of the limitation.
    https://msdn.microsoft.com/en-us/library/ff878370.aspx
    What are you trying to do? Can you give us an example and required output?
    --Prashanth

  • How to use pl/sql code as ODI user defined function

    Hi All,
    i have a pl/sql code and i want to create ODI user defined function using this code .
    please find the pl/sql code below:
    ============================
    declare
    v_no_of_duplicate_rec number := 0;
    begin
    select count(*)
    into v_no_of_duplicate_rec
    from ( select 1
    from temp_pre_selections
    group by svb_number, selection_id
    having count(*) > 1);
    if v_no_of_duplicate_rec = 0 then
    return 'N';
    else
    return 'Y';
    end if;
    end if;
    ==========================
    please help me how to achieve the same .
    Thanks
    Vinod

    2 ways:
    a. implement logic in odi function directly: getCount, Oracle implementation:
    select case count(1) when 0 then 'N' else 'Y' end
    from hr.employees
    when you use this function to refresh a variable, the refresh statement should only be getCount, you shoueld not write select getCount from dual, otherwise it will become
    select select .... from ... from dual
    b. if your logic is complex, I suggest to write function directly in your database, then call this function in your ODI function
    eg:
    CREATE OR REPLACE FUNCTION hr.test RETURN varchar2 IS
    tmpVar NUMBER;
    BEGIN
    select count(1) into tmpVar from hr.employees;
    if tmpVar=0 then
    return 'N';
    else
    return 'Y';
    end if;
    END test;
    then create a ODI function, Oracle implementation is
    hr.test
    in your variable refresh statement, you can write select getCount from dual
    if you use the odi function in other locations expect for refreshing variable, the idea is similar

  • Where are User Defined Functions and Stored Procedures kept in SQL Server?

    Hi,
    I have a growing list of Stored Procedures and User-Defined Functions in SQL Server, and would like to be able to list all my user SP and UDF easily.
    Is it possible to write a query to list all SP and UDF?
    I saw the following specimen code in an SQL book, but am not sure this is what I need because I could not make it work.
    SELECT *
        FROM INFORMATION_SCHEMA.ROUTINES
    WHERE SPECIFIC_SCHEMA = N'CustomerDetails'
        AND SPECIFIC_NAME = N'apf_CusBalances'
    I tried:
    SELECT *
        FROM INFORMATION_SCHEMA.ROUTINES
    but it does not work.
    Suppose all my SP are named following this pattern:
        dbo.usp_Storeproc1
    How would I modify the above code? or is there a better code?
    Thanks
    Leon Lai

    Hi ,
    try this to get list of all stored procedures:
    SELECT *
    FROM sys.procedures where name like 'dbo.usp%'
    Thanks,
    Neetu

  • Are Sql functions different from user defined functions ?

    Hello,
    SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not >confuse SQL functions with user-defined functions written in PL/SQL.according to first paragraph of this document Sql functions are different from user defined functions . How is that ?
    Is they really differ from each other ?

    bootstrap wrote:
    If you don't know what compilation is, please use Wikipedia or other online resources.I know what is compilation . But i was confused whether those sql functions are compiled in my machine when i install Oracle Database in my machine or they are pre-compiled .
    As you said these Sql functions are pre-compiled , it is clear now that they are pre-compiled platform dependent code .
    Can you provide actual source code of any SQL function , say SUM function .
    I want to see it, how they have defined . Eagerly waiting for any reply. please help .
    Edited by: bootstrap on Aug 19, 2011 11:50 AMYou can ask oracle if they give you their code. I doubt they will. However if you want to write you own user-defined aggregation function, there are examples in the documentation how to do that.
    http://download.oracle.com/docs/cd/E11882_01/appdev.112/e17125/adfns_packages.htm#i1008575
    Edited by: Sven W. on Aug 19, 2011 9:24 AM

  • How to migrate sql server 2000 user defined function returns table

    Hi,
    How do I capture the SQL Server 200 user defined function that returns table? Is this supported in the current version of Oracle Migration Workbench? I am using the latest version - Release 9.2.0.1.0 with SQL SERVER 2000 plug-in.
    I was able to capture the SQL Server 2000 user defined function that returns string and smalldatetime but not the functions return table during the migrate data source stage.
    Thanks in Advance,
    Susan

    Susan,
    This is not currently supported. The next release of the Oracle Migration Workbench (due very soon), will do a better job of catching this mad reporting an error. We are looking into a suitable mapping and have created bug # 2355073 - TABLE DEFINITIONS NOT ACCEPTED FOR TABLE FUNCTIONS to track this issue.
    Once possible solution we are looking into is using the object type to emulate. Here is an example from the bug:
    Original table
    SQL> create table tabela (a number, b number, c number, d number);
    SQL> insert some values...
    SQL> select * from tabela;
    A B C D
    1 1 1 1
    2 2 2 2
    3 3 3 3
    4 4 4 4
    SQL Server 2000 code
    CREATE FUNCTION FUNCRETORNATABELA()
    RETURNS TABLE
    AS
    RETURN SELECT A,B,C,D FROM TABELA
    SELECT A,B,C,D
    FROM FUNCRETORNATABELA()
    ORDER BY A
    Oracle code (workaround)
    SQL> create or replace type MyObjType as object (
    2 a number, b number, c number, d number);
    3 /
    Type created.
    SQL> create or replace type MyTabType as table of MyObjType;
    2 /
    Type created.
    SQL> create or replace function teste return Mytabtype pipelined as
    2 aa MyObjType := MyObjType(null, null, null, null);
    3 cursor c1 is select a,b,c,d from tabela;
    4 begin
    5 open c1;
    6 loop
    7 fetch c1 into aa.a, aa.b, aa.c, aa.d;
    8 exit when c1%NOTFOUND;
    9 pipe row (aa);
    10 end loop;
    11 close c1;
    12 return;
    13 end;
    14 /
    Function created.
    SQL> select * from table(teste);
    A B C D
    1 1 1 1
    2 2 2 2
    3 3 3 3
    4 4 4 4
    SQL> select a, c from table(teste) order by c desc;
    A C
    4 4
    3 3
    2 2
    1 1
    Donal

  • USER DEFINED FUNCTIONS IN FORM 6i

    I am interested to learn how can I manipulate, call a database user define function in a form6i that I am now using. It should give me desire database information on the forms? I am sorry, if I could explain the topics?
    Thanks & regards
    Dharani Barman

    Just call the function from PL/SQl or SQL in your Forms code - it shoudl all work providing that the user you are connected as has access to and execution rights on that function, and that the function uses parameters and return types that are compatible with the version of PL/SQL that the Forms engine has.

  • User Defined Function (Part 2)

    Hi,
    István Korös has finally solved my problem on User Defined Function.
    See
    My objective was to write a simple UDF to represent the following formula which Gordon Du gave me:
    (DATEADD (s, -1, 
             DATEADD (mm, (DATEDIFF (m,0,@refdtzz ) + @mthnumber),  0)))
    However, the solution proposed by István, although it works perfectly, leaves me scratching my head. Let's see why?
    The only difference between my solution and that proposed by István is that István enclosed the UDF name between .
    I wonder how this can make the vital difference between a (simple query!) that works well and one that gets blocked.
    I tried several combinations of and am in for a few surprises, listed below. Can anybody explain what's going on?
    Solution proposed by István:
    CREATE FUNCTION [dbo].[udf_EndOfMonth]
    and executed as:
    select  [dbo].udf_EndOfMonth (@refdt1 , 1)
    Remarks: works perfectly
    If I execute the UDF with exaclly the same name as in CREATE, it does not work
    CREATE FUNCTION [dbo].[udf_EndOfMonth]
    and executed as:
    select  [dbo].[udf_EndOfMonth] (@refdt1 , 1)
    Error Msg: Must specify table to select from
    If I don't put the , the function is created, but the execution of the calling query returns error
    CREATE FUNCTION dbo.udf_EndOfMonth
    Remarks : Creation OK
    and executed as:
    select  dbo.udf_EndOfMonth (@refdt1 , 1)
    Error Msg: Must specify table to select from
    It seems that the only combination that works is that provided by István.
    This is surely a simple UDF.
    I don't know what to do if I attack a more complicated UDF.
    Grateful if anybody could help light my way.
    Thanks
    Leon Lai

    Hi Leon,
    As István has already pointed out, there is no documentation for those small differences to make the SQL work or not. He must be tested quite a few times to find the actual working code. This question can only be answered by the developer who made this part for B1.
    Thanks,
    Gordon

Maybe you are looking for

  • How to select columns in a table by their column id and not the column name

    Hello, How do you select columns from a table based on their column_id. I have create a view but other than Select * , i cant now select one just one column from it the view as follow: create view count_student as select a.acode "acode",aname "Activi

  • F.13. Automatic Clearing ... Special G/L transaction

    Hi: I have a problem in FI, and perhaps you know how to solve it. We want to run F.13 transaction, but it does not work for Special G/L transaction (Customer accounts). I have checked data in transaction OB74, and everything seems to be ok. We have n

  • Trading ipod 4th generation to the 5th

    Hi! I bought an ipod4th generation 8GB is it possible for me to trade it with the 5th generation? by the way I bought the ipod4 like about 5-6 months ago

  • Error when dragging tree item - get firstVisibleItem

    I have been trying to debug this for hours but I can't determine any reason behind this error. I have a tree which I am populating with Array collections.  The items in the array collection have views which I am adding to a canvas, however when I add

  • Table cell boarders re-appearing

    Hi - Has anyone run into an issue where they remove the boarder around a cell only to have it re-appear the next time you open the layout template? If so, did you find a way around it? Thanks - CC