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]

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.

  • Make CFL for user defined tables in Crystal Report 8.8 ?

    Hi Experts
    Use Follwing qry for CFL ( user defined tables) in Crystal Report But its not Show CFL after run the Report in SAP B1 8.8
    Period@Select T0.*  from @OICC T0
    Thanks & Regards
    Dinesh Lade

    Hi,
    As far as i know, SBO can't figure out in such instance what are you doing, try linking it to an original table.
    I usually use OADM for this purpose.
    Hope this helps.
    Regards,
    Daniel

  • ? 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.

  • How to use StreamTransformationException in user-defined function?

    Hi,
    I'm doing a DBLookup (using Java pgm in one of my Imported Java archives) for populating one of the fields in message mapping. If the DB connection fails, I want to terminate the mapping by throwing a StreamTransformationException from within a user-defined function.
    I require urgent help in this regard.
    Thanks in advance.
    Regards,
    Sridhar Rajan N

    Hi,
    I had the same problem. I failed to find the way how to throw a StreamTransformationException in my user-defined function. But I used another exception: NullPointerException. Yes, I know, this is not an elegant solution...
    Best regards,
    Andrzej Filusz

  • Using a scalar user defined function in a select case statement

    I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
    ZIPCODE' below.
    SELECT
        CASE
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             ELSE NULL
           END as Zipcode,
    FROM
    table1

    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]

  • Error while using user defined function in reports

    Hi,
    When I use the below user defined function in oracle reports I got the wrong number of arguments error
    select test_function(id,a_number,v_date-14,b_number) from dual;
    If I remove -14 from the argument it works. But iIneed to subtract 14 days from the date.
    Thanks for your help.

    select test_function(id,a_number,v_date-14,b_number) from dual;
    you have to give the command like this to_date(v_date,'dd-mon-yyyy')-14
    because the v_Date you choose in the parameter form is not having the corrent date format
    the format dd-mon-yyyy is the format in which v_date is passed by the user.

  • Using Xquery predefined functions in User defined functions

    Hi All,
    I have a requirement of calling a user defined function in osb xquery file.In that function i have to use osb predefined string functions but they are not working it shows error message in xquery file.Can you please suggest how to use them in user defined functions.
    Thanks,
    Srinivas.

    Hi Eric,
    I have a Proxy service it reads mfl data and transform to some other schema.In this Transformation one element data is taken and we have to manipulate that data
    based on the incoming value and return .For this process i took one function and i have to check weather it contains some symbols like ^,~ so i used contains function of
    String with and with out prefix with if else condition it gives error "Unexpected token if"
    declare function insp:buildReferenceRange($inRange as xs:string)
    as xs:string
    let $low:=""
    l
    if(contains($inRange,"^")) //"Unexpected token if"
    name space and prefix are defined in the top of file.
    Thanks,
    Srinivas.

  • User defined function in PI 7.1 compilation error "Recompile with -Xlint"

    Hi All,
    I have a user defined function in PI 7.1 .,which is throwing the following error.
    Do i need to add any import statements like "import java.lang.String" in the beginning.
    It is unable to recognize the String methods used in the user defined function.
    E:\usr\sap\PID\DVEBMGS30\j2ee\cluster\server0\.\temp\classpath_resolver\Map02580a102a0911deb2b20019990eddfd\source\com\sap\xi\tf\_MM_C_to_Goods_.java:276:
    cannot find symbol
    symbol : method trim()
    location: class java.lang.Object
    if(container.getParameter("AdjustmentQuantity").trim().startsWith("-")){ ^
    Note: E:\usr\sap\PID\DVEBMGS30\j2ee\cluster\server0\.\temp\classpath_resolver\Map02580a102a0911deb2b20019990eddfd\source\com\sap\xi\tf\_MM_C_to_Goods_.java
    uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    Note: E:\usr\sap\PID\DVEBMGS30\j2ee\cluster\server0\.\temp\classpath_resolver\Map02580a102a0911deb2b20019990eddfd\source\com\sap\xi\tf\_MM_C_to_Goods_.java
    uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Any Help greatly appreciated..
    Collins

    container.getParameter() returns Object, not String.
    try following:
    String aq = (String) container.getParameter("AdjustmentQuantity");
    if(aq.trim().startsWith("-"))
    Regards
    Stefan

  • Determine Element maxLenght in User-Defined Function

    Hi,
    I have the problem, that I have to fill up several fields with leading 0. I wrote a User-Defined Function for this. But the function doesn't know how long this element is, so I have to give the function the length of the element.
    Is it possible to determine the length of the current element in an extended User-Defined Function
    Yours
    Thomas

    Hi,
    >use a simple user defined function with the desired
    >source element as input and give the following code...
    >int k = a.length();
    >String len = Integer.toString(k);
    >return len;
    That function will only give me the actual lenght of the input element, what I need is the max lenght of the target element...
    >You can also use the built-in FormatNumber function to
    >insert leading 0s.
    How can I use this function to add leading zeros?
    "'000'#" ? But there I have to do this for every element
    >I think an easy solution for this is, just have a
    >simple function with two arguments. The first is the
    >element, the second is a constant, where you put the
    >length.
    Well I have this function. But I am looking for way to the safe the second argument ;o)
    Thank you all for your help
    Thomas

  • How many types of user defined functions are there?

    how many types of user defined functions are there?

    Hi Ramakrishna,
    A user-defined function is only visible in the message mapping in which you created it. You can insert the function in the data-flow editor as a standard function by using the User-Defined function category.
    You can use the following user-defined functions:
    1.Simple functions, which can process individual field input values for each function call. Simple functions therefore expect strings as input values and return a string.
    2.Advanced functions, which can process several field input values for each function call. You can import either all field values of a context or the whole queue for the field in an array before calling the function. For more information, see Advanced User-Defined Functions.
        go through :
    http://help.sap.com/saphelp_erp2004/helpdata/en/22/e127f28b572243b4324879c6bf05a0/content.htm
         Advanced user-defined functions, which can process more than just individual field values.Instead, you can import a complete context or an entire queue for a field as an array before your function is called
        go through :
    http://help.sap.com/saphelp_erp2004/helpdata/en/f8/2857cbc374da48993c8eb7d3c8c87a/content.htm
    *Pls: Reward points if helpful*
    Regards,
    Jyoti

  • Advanced User Defined Function

    Dear All,
    I have a target structure as follows:
    <Item>
       <Record10>
          <RecordType>
          <BankCode>
          <AccountID>
          <Amount>
       </Record10>
       <Record50>
          <RecordType>
          <Segment1>
          <segment2>
          <segment3>
       </Record50>
    </Item>
    I want to fill the elements in the Record50 in a special way by using some logic. Sometimes I may have to create multiple Record50 structures. So I'm using an advanced user defined function to do this.
    My mapping is as follows:
    Source Structure -> myFunction()->Record50
    And in myFunction() I wrote the following piece of code:
    result.addValue("50");
    result.addValue("PayRef1");
    result.addValue("Address");
    result.addValue("Nil");
    I expect the output to be:
       <Record50>
          <RecordType>50</RecordType>
          <Segment1>PayRef1</Segment1>
          <segment2>Address</segment2>
          <segment3>Nil</segment3>
       </Record50>
    But the output is like this:
    <Record50>50</<Record50>
    <Record50>PayRef1</<Record50>
    <Record50>Address</<Record50>
    <Record50>Nil</<Record50>
    Can somebody tell me how to proceed? I tried to insert a context change in the beginning, but then the Record50 itself is not appearing.
    Thanks,
    Sandeep

    Hi,
    Advanced UDF will not create you like you expected.
    You need to do like this
    Source>myFunction1()-><RecordType>
    And in myFunction() you do code:
    result.addValue("50");
    Source>myFunction2()-><Segment1>
    And in myFunction2() you do code:
    result.addValue("PayRef1");
    so on..
    Thanks,
    Prakash

  • 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. ;)

Maybe you are looking for