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]

Similar Messages

  • 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]

  • 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

  • Calling a user defined function in a select statement

    PLS-00231: function 'F_GET_PROJECT_ID' may not be used in SQL
    I am caling a user defined function 'F_GET_PROJECT_ID' in a select statement and getting the above error .
    Can any one help me to resolve it.
    I can not replace the function with a local variable nor can I assign the output of the function to a variable and use the variable in the sql stmt. cos, the in put parameters of the function comes from the same select statement.
    Please help
    Thanks in advance

    Can you provide your function code? Using a function like that is possible from the below example. I suspect something in your function code.
    SQL> create or replace function sample_func(p_sal number)
      2  return number
      3  is
      4  v_sal number;
      5  begin
      6     v_sal := p_sal+100;
      7     return v_sal;
      8  end;
      9  /
    Function created.
    SQL>
    SQL> select empno, ename, sal, sample_func(sal)
      2  from emp
      3  /
         EMPNO ENAME             SAL SAMPLE_FUNC(SAL)
          7839 KING             5000             5100
          7698 BLAKE            2850             2950
          7782 CLARK            2450             2550
          7566 JONES            2975             3075
          7654 MARTIN           1250             1350
          7499 ALLEN            1600             1700
          7844 TURNER           1500             1600
          7900 JAMES             950             1050
          7521 WARD             1250             1350
          7902 FORD             3000             3100
          7369 SMITH             800              900
          7788 SCOTT            3000             3100
          7876 ADAMS            1100             1200
          7934 MILLER           1300             1400
    14 rows selected.
    SQL>And yeah... your formatted code is this.
    cursor c1 is
       SELECT t.upi_nbr upi_nbr,
              f_get_project_id(l.pay_type_code,
                               l.charge_type_nme,
                               l.charge_code) project_id,
              LAST_DAY(TO_DATE(SUBSTR(t.Year_Month, 5, 2)||'/'||'01'||'/'||SUBSTR(t.Year_Month,1,4),
                               'MM/DD/YYYY'))reporting_period_end_date,
              SUM (c.hours_worked_qty) reported_hrs
       from trs.trs_timesheet@oraprod5 T,
            trs.trs_line@oraprod5 L,
            trs.trs_cell@oraprod5 C
    where T.upi_nbr=L.upi_nbr
    and T.year_month=L.year_month
    and L.row_nbr=C.row_nbr
    and L.upi_nbr=C.upi_nbr
    and L.year_month = C.year_month
    and L.invalid_activity_ind = 'V'
    and rtrim(L.charge_code) is not null
    AND L.Pay_Type_Code<>'REQ'
    and C.Hours_Worked_Qty > 0
    GROUP BY t.upi_nbr,
             t.year_month,
             t.oui_nbr,
             l.charge_code,
             l.activity_detail_code,
             l.charge_type_nme,
             l.pay_type_code;Cheers
    Sarma.

  • 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

  • User defined function in a cursor

      Hi All,
    I  need to use a user defined function(which returns a value based on my Procedure's input parameter) in my explicit cursor. Something like
    create or replace procedure test(pi_input number)
    cursor c1
    is
    select  col1,
               col2,
              func(pi_input),
              col4
    from table;
    begin
    end;
    Is this possible? I

    Hi,
    User-defined functions can appear in SQL statements, including cursors, if they follow certain rules (e.g., all arguments are IN arguments, in one of the SQL data types).
    You really need to post your code. You don't need to post the compete code; a simplified version that gets the same error would serve just as well (actually better).  Include CREATE TABLE and INSERT statements for any tables used, the function code, the code that calls the function, and the results you want from that code, given the sample data you posted.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002
    Does your function work the way you want when it is not in a cursor?

  • 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

  • User Defined Function in MV

    Hello All,
    Can we have user defined function in the select clause of a materializied view.
    I am aware that we cannot have subquery in the select clause of MV.
    Regards,
    Kumar.

    That's not hard to test ...
    SQL> create function f return varchar2
      2  is
      3  begin
      4    return 'I''m from function f';
      5  end;
      6  /
    Functie is aangemaakt.
    SQL> create materialized view my_mv
      2  as
      3  select empno
      4       , ename
      5       , f
      6    from emp
      7  /
    Gematerialiseerde view is aangemaakt.
    SQL> column f format a30
    SQL> select * from my_mv
      2  /
         EMPNO ENAME      F
          7369 SMITH      I'm from function f
          7499 ALLEN      I'm from function f
          7521 WARD       I'm from function f
          7566 JONES      I'm from function f
          7654 MARTIN     I'm from function f
          7698 BLAKE      I'm from function f
          7782 CLARK      I'm from function f
          7788 SCOTT      I'm from function f
          7839 KING       I'm from function f
          7844 TURNER     I'm from function f
          7876 ADAMS      I'm from function f
          7900 JAMES      I'm from function f
          7902 FORD       I'm from function f
          7934 MILLER     I'm from function f
    14 rijen zijn geselecteerd.If you want the materialized view to be fast refreshable, then the answer is no.
    Regards,
    Rob.

  • Error in conditional map using User Defined Function

    All,
    In my mapping I basically have a user defined function that returns the filename of my inbound file from the adapter-specific message attributes (file adapter).  I know this is coded properly because if I simply assign this function to my destination field I can see the filename in the payload XML.
    However if I conditionally check that returned value using if,then,else I get an error message stating:
    "During the application mapping com/sap/xi/tf/_MaterialData2ZcustProdMastMulti_ a com.sap.aii.utilxi.misc.api.BaseRuntimeException was thrown: RuntimeException in Message-Mapping transformation"
    Essentially in my if I'm checking if the value returned by my user defined function is equal to the constant "SOMECONSTANT" then I'm setting my destination field to some other constant value.  Otherwise it's equal to a different constant value.
    Any thoughts?

    Claus,
    Thanks for the help.  I actually had figured the problem out on my own.  Sorry for not updating the thread sooner.  What happened was this (as I suspected it wasn't related to my user defined function).  For the newbies out there (of which I'm one) the problem was I was comparing strings in the graphical mapping tool using the Boolean "EQUALS" rather than the Text "EQUALSS".
    Can you give yourself points for solving

  • How can I use Seeburger java functions on SAP XI's user defined functions?

    Hi All,
    As my title implies; how can I use Seeburger java functions on SAP XI's user defined functions?  I've tried searching over the net in tutorials regarding this topic but I failed to find one; can someone provide me information regarding my question? thanks very much.
    best regards,
    Mike

    Hi Mike !
    You should check your documentation about which java classes you need to reference in the "import" section of your UDF. And also deploy the java classes into the java stack or include them as a imported archive in integration repository...it should be stated in the seeburger documentation.
    What kind of functions are you trying to use?
    Regards,
    Matias.

  • How to resolve the error while using user defined function.

    EPN Assembly file
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:osgi="http://www.springframework.org/schema/osgi"
    xmlns:wlevs="http://www.bea.com/ns/wlevs/spring"
    xmlns:jdbc="http://www.oracle.com/ns/ocep/jdbc"
    xmlns:spatial="http://www.oracle.com/ns/ocep/spatial"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd
    http://www.bea.com/ns/wlevs/spring
    http://www.bea.com/ns/wlevs/spring/spring-wlevs-v11_1_1_3.xsd
    http://www.oracle.com/ns/ocep/jdbc
    http://www.oracle.com/ns/ocep/jdbc/ocep-jdbc.xsd
    http://www.oracle.com/ns/ocep/spatial
    http://www.oracle.com/ns/ocep/spatial/ocep-spatial.xsd">
         <wlevs:event-type-repository>
              <wlevs:event-type type-name="TestEvent">
                   <wlevs:class>com.bea.wlevs.event.example.FunctionCEP.TestEvent</wlevs:class>
              </wlevs:event-type>
         </wlevs:event-type-repository>
         <wlevs:adapter id="InputAdapter"
              class="com.bea.wlevs.adapter.example.FunctionCEP.InputAdapter">
              <wlevs:listener ref="inputStream" />
         </wlevs:adapter>
         <wlevs:channel id="inputStream" event-type="TestEvent">
              <wlevs:listener ref="processor" />
         </wlevs:channel>
         <wlevs:processor id="processor">
              <wlevs:listener ref="outputStream" />
              <wlevs:function function-name="sum_fxn" exec-method="execute">
              <bean>com.bea.wlevs.example.FunctionCEP.TestFunction</bean>
              </wlevs:function>
         </wlevs:processor>
         <wlevs:channel id="outputStream" event-type="TestEvent">
              <wlevs:listener ref="bean" />
         </wlevs:channel>
         <bean id="bean" class="com.bea.wlevs.example.FunctionCEP.OutputBean">
         </bean>
    </beans>
    Event class
    package com.bea.wlevs.event.example.FunctionCEP;
    public class TestEvent {
         private int num_1;
         private int num_2;
         private int sum_num;
         public int getSum_num() {
              return sum_num;
         public void setSum_num(int sumNum) {
              sum_num = sumNum;
         public int getNum_1() {
              return num_1;
         public void setNum_1(int num_1) {
              this.num_1 = num_1;
         public int getNum_2() {
              return num_2;
         public void setNum_2(int num_2) {
              this.num_2 = num_2;
    Adapter class
    package com.bea.wlevs.adapter.example.FunctionCEP;
    import com.bea.wlevs.ede.api.RunnableBean;
    import com.bea.wlevs.ede.api.StreamSender;
    import com.bea.wlevs.ede.api.StreamSource;
    import com.bea.wlevs.event.example.FunctionCEP.TestEvent;
    public class InputAdapter implements RunnableBean, StreamSource {
    private StreamSender eventSender;
    public InputAdapter() {
    super();
    public void run() {
         generateMessage();
    private void generateMessage() {
         TestEvent event = new TestEvent();
         event.setNum_1(10);
         event.setNum_2(20);
         eventSender.sendInsertEvent(event);
    public void setEventSender(StreamSender sender) {
    eventSender = sender;
    public synchronized void suspend() {
    Output Bean class
    package com.bea.wlevs.example.FunctionCEP;
    import com.bea.wlevs.ede.api.StreamSink;
    import com.bea.wlevs.event.example.FunctionCEP.TestEvent;
    import com.bea.wlevs.util.Service;
    public class OutputBean implements StreamSink {
         public void onInsertEvent(Object event) {
              System.out.println("In Output Bean");
              TestEvent event1 = new TestEvent();
              System.out.println("Num_1 is :: " + event1.getNum_1());
              System.out.println("Num_2 is :: " +event1.getNum_2());
              System.out.println("Sum of the numbers is :: " +event1.getSum_num());
    Function Class
    package com.bea.wlevs.example.FunctionCEP;
    public class TestFunction {
         public Object execute(int num_1, int num_2)
              return (num_1 + num_2);
    config.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <wlevs:config xmlns:wlevs="http://www.bea.com/ns/wlevs/config/application"
    xmlns:jdbc="http://www.oracle.com/ns/ocep/config/jdbc">
         <processor>
              <name>processor</name>
                   <rules>
                   <view id="v1" schema="num_1 num_2">
                        <![CDATA[
                             select num_1, num_2 from inputStream     
                        ]]>
                   </view>
                   <view id="v2" schema="num_1 num_2">
                   <![CDATA[
                   select sum_fxn(num_1,num_2), num_2 from inputStream // I am getting error when i am trying to call this function
                   ]]>
                   </view>
                   <query id="q1">
                        <![CDATA[
                             select from v2[now] as num_2*     // Showing error while accessing the view also               ]]>
                   </query>
              </rules>
         </processor>
    </wlevs:config>
    Error I am getting is :
    Invalid statement: "select >>sum_fxn<<(num_1,num_2),age from inputStream"
    Description: Invalid call to function or constructor: sum_fxn
    Cause: Probable causes are: Function name sum_fxn(int,int) provided is invalid, or arguments are of
    the wrong type., or Error while handling member access to complex type. Constructor sum_fxn of type
    sum_fxn not found. or Probable causes are: Function name sum_fxn(int,int) provided is invalid, or
    arguments are of the wrong type., or Error while handling member access to complex type.
    Constructor sum_fxn of type sum_fxn not found.
    Action: Verify function or constructor for complex type exists, is not ambiguous, and has the correct
    number of parameters.
    I have made a user defined function in a java class and configured this function in the EPN assembly file under the processor tag.
    But when i am trying to access the function in the config.xml file , it is giving me an error in the query.
    Please provide urgent help that how to write the exact query.

    Hi,
    In the EPN Assembly file use
    <bean class="com.bea.wlevs.example.FunctionCEP.TestFunction"/>
    instead of
    <bean>com.bea.wlevs.example.FunctionCEP.TestFunction</bean>
    Best Regards,
    Sandeep

Maybe you are looking for

  • Why won't my OS 10.6.8  respond to HP Officeject 4620 print or scan.

    I upgraded my MacBook to OS 10.6.8 and purchased a HP Officeject 4620 all-in-one printer/scanner.  Had to return the printer because it wouldn't communicate with my MacBook.   Received a replacement printer and am having the same problems with it.  I

  • What printers are compatible with Mac Book Pro's?

    Hi All, Just looking to buy a printer for my Mac Book Pro but I don't know which ones are compatiable... Any suggestions or do you know where I can find a list of compatible printers?? Thanks

  • How to implement a keyListener in JSF/JSP

    Hello, I�m using JSC and want to implement a keyListener in my application. I want to press ENTER and a method in my java class should be called (regardless of the component, which has the focus). Is this possible (normally, a component must have the

  • IMessage dosen't work just with one contact

    hi, i used to write this person with iMessage, but today i couldn't.just sms.it doesen't try to write with iMessage but directly sent an sms.i can write anyone else with iMessage but this person, and this person can write anybody but me with iMessage

  • FileSystem Copy for BW3.5

    Hi, We have installed NW04 for BW3.5 on a HP Host. We plan to move it to a new HP UX server. All we will be doing is copying the file system from old host to the new host as the DB/System name will remain same. My question is: Since NW/WAS640 also ha