If statement in CE function

Hi,
When we use IF in calculation view with CE function the SQL engine is used.
When we remove the "IF" the  CE engine is used.
Is there any alternative for if or case in CE functions?
Thanks,
Amir

Is it possible to use CE_CALC for this functionality?
We are trying to use it inside projection:
res_bal = CE_PROJECTION (:bal,[ "BUDAT", "RYEAR" ,  "Bal_Date" AS "BALANCE_DATE",   "RTCUR" ,"MAX_ZGROUP"],'"BALANCE_DATE" == 20140101');
works but:
res_bal = CE_PROJECTION (:bal,[ "BUDAT", "RYEAR" ,  "Bal_Date" AS "BALANCE_DATE",   "RTCUR" ,"MAX_ZGROUP"], '"BALANCE_DATE" == CE_CALC( 'if(''20140101'' == ''19000101'', ''19000101'', ''20140101'')');
Doesn't work.
Thanks,
Amir

Similar Messages

  • Error while replacing IF statements with DECODE function in procedure

    Hi All,
    I have created a procedure which has nested IF statements. Now I want to replace the IF statements with DECODE functions to improve performance.
    Procedure:
    IF (var_int_sev = '0')
    THEN
    var_sev := '2';
    ELSE
    SELECT sev
    INTO var_int_sev
    FROM errorconfig
    WHERE errorcode = var_errorcode;
    var_sev := var_int_sev;
    END IF;
    I converted the above IF statement into DECODE function as mentioned below:
    var_Sev := DECODE(var_int_sev,0,2,SELECT severity FROM errorconfig WHERE errorcode=var_ErrorCode)
    But it throws below error at the select statement used inside DECODE.
    Error(58,51): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternativ
    Can someone help me in converting the IF to DECODE in the above case. Also how can we use a select statement inside decode.

    instead of trying to rewrite all your code and hoping that the performance will be better, it's a better option to investigate and find out which part of your application is slow
    read this:
    When your query takes too long ...

  • Case statement and Decode function both are not working in Select cursor.

    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. On the other hand both the things work in just select statement.
    See the first column in select (PAR_FLAG), I need to have this evaluated along with other fields. Can you please suggest some thing to make this work. And also I would like to
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Author : Amit Juneja
    Date : 06/20/2011
    Description:
    Updates the Diamond MEMBER_MASTER table with the values from
    INC.MEM_NJ_HN_MEMBER_XREF table.
    declare
    rec_cnt number(12) := 0;
    commit_cnt number(4) := 0;
    cursor select_cur is
    Select DECODE(1,
    (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY'))),
    'Y',
    'N') PAR_FLAG,
    H.SEQ_ELIG_HIST,
    H.SEQ_MEMB_ID,
    H.SEQ_SUBS_ID,
    H.SUBSCRIBER_ID,
    H.PERSON_NUMBER,
    H.EFFECTIVE_DATE,
    H.TERM_DATE,
    H.TERM_REASON,
    H.RELATIONSHIP_CODE,
    H.SEQ_GROUP_ID,
    H.PLAN_CODE,
    H.LINE_OF_BUSINESS,
    H.RIDER_CODE_1,
    H.RIDER_CODE_2,
    H.RIDER_CODE_3,
    H.RIDER_CODE_4,
    H.RIDER_CODE_5,
    H.RIDER_CODE_6,
    H.RIDER_CODE_7,
    H.RIDER_CODE_8,
    H.MEDICARE_STATUS_FLG,
    H.OTHER_STATUS_FLAG,
    H.HIRE_DATE,
    H.ELIG_STATUS,
    H.PREM_OVERRIDE_STEP,
    H.PREM_OVERRIDE_AMT,
    H.PREM_OVERRIDE_CODE,
    H.SEQ_PROV_ID,
    H.IPA_ID,
    H.PANEL_ID,
    H.SEQ_PROV_2_ID,
    H.SECURITY_CODE,
    H.INSERT_DATETIME,
    H.INSERT_USER,
    H.INSERT_PROCESS,
    H.UPDATE_DATETIME,
    H.UPDATE_USER,
    H.UPDATE_PROCESS,
    H.USER_DEFINED_1,
    H.SALARY,
    H.PEC_END_DATE,
    H.REASON_CODE,
    H.PEC_WAIVED,
    H.BILL_EFFECTIVE_FROM_DATE,
    H.BILLED_THRU_DATE,
    H.PAID_THRU_DATE,
    H.SUBSC_DEPT,
    H.SUBSC_LOCATION,
    H.USE_EFT_FLG,
    H.BENEFIT_START_DATE,
    H.SEQ_ENROLLMENT_RULE,
    H.MCARE_RISK_ACCRETION_DATE,
    H.MCARE_RISK_DELETION_DATE,
    H.MCARE_RISK_REFUSED_DATE,
    H.COMMENTS,
    H.USER_DEFINED_2,
    H.USER_DEFINED_3,
    H.RATE_TYPE,
    H.PCPAA_OCCURRED,
    H.PRIVACY_ON,
    H.PCP_CHANGE_REASON,
    H.SITE_CODE,
    H.SEQ_SITE_ADDRESS_ID,
    PM.seq_prov_id rendered_prov
    from hsd_member_elig_history H,
    INC.PCP_REASSIGN_RPRT_DATA P,
    hsd_prov_master PM
    where P.subscriber_id = H.subscriber_id
    and P.rendered_pcp = PM.provider_ID
    and H.elig_status = 'Y'
    and (H.term_date is NULL or H.term_date >= last_day(sysdate))
    order by H.Seq_memb_id;
    begin
    for C in select_cur loop
    rec_cnt := rec_cnt + 1;
    update hsd_member_elig_history
    set term_date = TRUNC(SYSDATE - 1),
    term_reason = 'PCPTR',
    update_datetime = SYSDATE,
    update_user = USER,
    update_process = 'TD33615'
    where seq_elig_hist = C.seq_elig_hist
    and seq_memb_id = C.seq_memb_id;
    INSERT INTO HSD_MEMBER_ELIG_HISTORY
    (SEQ_ELIG_HIST,
    SEQ_MEMB_ID,
    SEQ_SUBS_ID,
    SUBSCRIBER_ID,
    PERSON_NUMBER,
    EFFECTIVE_DATE,
    TERM_DATE,
    TERM_REASON,
    RELATIONSHIP_CODE,
    SEQ_GROUP_ID,
    PLAN_CODE,
    LINE_OF_BUSINESS,
    RIDER_CODE_1,
    RIDER_CODE_2,
    RIDER_CODE_3,
    RIDER_CODE_4,
    RIDER_CODE_5,
    RIDER_CODE_6,
    RIDER_CODE_7,
    RIDER_CODE_8,
    MEDICARE_STATUS_FLG,
    OTHER_STATUS_FLAG,
    HIRE_DATE,
    ELIG_STATUS,
    PREM_OVERRIDE_STEP,
    PREM_OVERRIDE_AMT,
    PREM_OVERRIDE_CODE,
    SEQ_PROV_ID,
    IPA_ID,
    PANEL_ID,
    SEQ_PROV_2_ID,
    SECURITY_CODE,
    INSERT_DATETIME,
    INSERT_USER,
    INSERT_PROCESS,
    UPDATE_DATETIME,
    UPDATE_USER,
    UPDATE_PROCESS,
    USER_DEFINED_1,
    SALARY,
    PEC_END_DATE,
    REASON_CODE,
    PEC_WAIVED,
    BILL_EFFECTIVE_FROM_DATE,
    BILLED_THRU_DATE,
    PAID_THRU_DATE,
    SUBSC_DEPT,
    SUBSC_LOCATION,
    USE_EFT_FLG,
    BENEFIT_START_DATE,
    SEQ_ENROLLMENT_RULE,
    MCARE_RISK_ACCRETION_DATE,
    MCARE_RISK_DELETION_DATE,
    MCARE_RISK_REFUSED_DATE,
    COMMENTS,
    USER_DEFINED_2,
    USER_DEFINED_3,
    RATE_TYPE,
    PCPAA_OCCURRED,
    PRIVACY_ON,
    PCP_CHANGE_REASON,
    SITE_CODE,
    SEQ_SITE_ADDRESS_ID)
    values
    (hsd_seq_elig_hist.nextval,
    C.SEQ_MEMB_ID,
    C.SEQ_SUBS_ID,
    C.SUBSCRIBER_ID,
    C.PERSON_NUMBER,
    trunc(SYSDATE),
    C.TERM_DATE,
    C.TERM_REASON,
    C.RELATIONSHIP_CODE,
    C.SEQ_GROUP_ID,
    C.PLAN_CODE,
    C.LINE_OF_BUSINESS,
    C.RIDER_CODE_1,
    C.RIDER_CODE_2,
    C.RIDER_CODE_3,
    C.RIDER_CODE_4,
    C.RIDER_CODE_5,
    C.RIDER_CODE_6,
    C.RIDER_CODE_7,
    C.RIDER_CODE_8,
    C.MEDICARE_STATUS_FLG,
    C.OTHER_STATUS_FLAG,
    C.HIRE_DATE,
    C.ELIG_STATUS,
    C.PREM_OVERRIDE_STEP,
    C.PREM_OVERRIDE_AMT,
    C.PREM_OVERRIDE_CODE,
    C.SEQ_PROV_ID,
    C.IPA_ID,
    C.PANEL_ID,
    C.SEQ_PROV_2_ID,
    C.SECURITY_CODE,
    SYSDATE,
    USER,
    'TD33615',
    SYSDATE,
    USER,
    'TD33615',
    C.USER_DEFINED_1,
    C.SALARY,
    C.PEC_END_DATE,
    C.REASON_CODE,
    C.PEC_WAIVED,
    C.BILL_EFFECTIVE_FROM_DATE,
    C.BILLED_THRU_DATE,
    C.PAID_THRU_DATE,
    C.SUBSC_DEPT,
    C.SUBSC_LOCATION,
    C.USE_EFT_FLG,
    C.BENEFIT_START_DATE,
    C.SEQ_ENROLLMENT_RULE,
    C.MCARE_RISK_ACCRETION_DATE,
    C.MCARE_RISK_DELETION_DATE,
    C.MCARE_RISK_REFUSED_DATE,
    C.COMMENTS,
    C.USER_DEFINED_2,
    C.USER_DEFINED_3,
    C.RATE_TYPE,
    C.PCPAA_OCCURRED,
    C.PRIVACY_ON,
    C.PCP_CHANGE_REASON,
    C.SITE_CODE,
    C.SEQ_SITE_ADDRESS_ID);
    commit_cnt := commit_cnt + 1;
    if (commit_cnt = 1000) then
    dbms_output.put_line('Committed updates for 1000 records.');
    commit;
    commit_cnt := 0;
    end if;
    end loop;
    commit;
    dbms_output.put_line('Total number of MEMBER_ELIG_HISTROY records inserted : ' ||
    rec_cnt);
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    end;

    user10305724 wrote:
    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. Please define what you mean by not working even if your computer screen is near the internet we can't see it.
    You should also look at the FAQ about how to ask a question
    SQL and PL/SQL FAQ
    Particularly *9) Formatting with {noformat}{noformat} Tags* and posting your version.
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Does this mean you are using 8i? Then scalar sub queries - selects within the select list, are not supported, along with CASE in PL/SQL.
    Select DECODE(1,
    * (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY')))*,
    'Y',
    'N') PAR_FLAG,
    >
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Is it possible to remember state in Java functions?

    I'm trying to graduate from C to Java, largely skipping C++ in the process. Both for fun, and as a learning experience, I'm converting a C program I wrote almost 7 years ago to Java, which computes sunrise & sunset given one's latitude and longitude (downloadable as http://alumni.caltech.edu/~tfly/sun.zip ).
    A technique I sometimes used in C programs was to have a "first_time" variable in a function. If that function was being executed for the "first time," it would know to perform this or that initialization of various variables. Such a variable would be declared as "static" within the function (it would retain its state from one function call to the next). Often, I would do this simply as a matter of efficiency- to avoid having to do the same calculation over and over again:
    /* Return the angle swept out since the Perihelion passage, "days_elapsed" ago.
    double orbit(days_elapsed)
    double days_elapsed;
         double x, y, cos_rads, radians;
         static char first_time = 1;
         static char *eccentricity = "\r\nEccentricity = 0.12345678";
         static double ecc, ecc_const, sqrt_const;
         if (first_time)
              first_time = 0;
              ecc = (double) APHELION_DIST / (double) AU_DISTANCE - 1;
              sprintf(eccentricity, "\r\nEccentricity = %.8f", ecc);
              output(eccentricity);
              sqrt_const = sqrt(1 - pow(ecc, 2));
              ecc_const = 2 * PI / SIDEREAL_YEAR;
    ...An obvious work-around (kluge) in Java would be to have class variables first_time_x specific to each function x that might want to know whether or not it's being called for the first time since the program was started.
    My question has more to do with philosophy and program design. Is this a significant flaw in Java, or am I simply using a feature of C that lets me take the easy way out of a fundamental design problem?

    Java doesn't have a concept of C-style static variables. You are supposed to remember things like this in object data members. Rather than use a counting integer, use "boolean initialized = false;" and assign it to true in your method with:
    if (initialized == false) {
    initialized = true;
    Look at it this way, in C you'll have a separate variable for each function, all with different names. All you are doing in Java is moving that variable to the next wider scope - object level instead of method level.
    If your functions form some kind of logical hierarchy, you can place the boolean initializer in the base class along with a method to perform the if() check. Then the only thing that changes is the implementation of the function in the derived classes. If you do it right, the polymorphic features of Java will call the right methods for the respective objects and you won't have to worry about a thing.
    You said you skipped C++, so if some of this OOP terminology is too foreign, drop me a line at [email protected] and we can discuss it at length and I can save on the phone bills :-)

  • IF statement in Standard function module PRICING

    Hi,
    In standard function module PRICING
    I found one if statement like this.
    if  xkomv-kntyp na '1$' .
    Plz tell me the meaning of thai '1$' value.
    Regards,
    Upender Verma.

    Hi,
         NA means Contains Not Any ..
         if xkomv-kntyp na '1$'  means .. xkomv-kntyp does not contain '1' or '$'.
         Read help on comparision operator 'NA'
    Regards,
    Srini.

  • Select statement in a function does Full Table Scan

    All,
    I have been coding a stored procedure that writes 38K rows in less than a minute. If I add another column which requires call to a package and 4 functions within that package, it runs for about 4 hours. I have confirmed that due to problems in one of the functions, the code does full table scans. The package and all of its functions were written by other contractors who have been long gone.
    Please note that case_number_in (VARCHAR2) and effective_date_in (DATE) are parameters sent to the problem function and I have verified through TOAD’s debugger that their values are correct.
    Table named ps2_benefit_register has over 40 million rows but case_number is an index for that table.
    Table named ps1_case_fs has more than 20 million rows but also uses case_number as an index.
    Select #1 – causes full table scan runs and writes 38K rows in a couple of hours.
    {case}
    SELECT max(a2.application_date)
    INTO l_app_date
    FROM dwfssd.ps2_benefit_register a1, dwfssd.ps2_case_fs a2
    WHERE a2.case_number = case_number_in and
    a1.case_number = a2.case_number and
    a2.application_date <= effective_date_in and
    a1.DOCUMENT_TYPE = 'F';
    {case}
    Select #2 – runs – hard coding values makes the code to write the same 38K rows in a few minutes.
    {case}
    SELECT max(a2.application_date)
    INTO l_app_date
    FROM dwfssd.ps2_benefit_register a1, dwfssd.ps2_case_fs a2
    WHERE a2.case_number = 'A006438' and
    a1.case_number = a2.case_number and
    a2.application_date <= '01-Apr-2009' and
    a1.DOCUMENT_TYPE = 'F';
    {case}
    Why using the values in the passed parameter in the first select statement causes full table scan?
    Thank you for your help,
    Seyed
    Edited by: user11117178 on Jul 30, 2009 6:22 AM
    Edited by: user11117178 on Jul 30, 2009 6:23 AM
    Edited by: user11117178 on Jul 30, 2009 6:24 AM

    Hello Dan,
    Thank you for your input. The function is not determinsitic, therefore, I am providing you with the explain plan. By version number, if you are refering to the Database version, we are running 10g.
    PLAN_TABLE_OUTPUT
    Plan hash value: 2132048964
    | Id  | Operation                     | Name                    | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT              |                         |   324K|    33M|  3138   (5)| 00:00:38 |       |       |
    |*  1 |  HASH JOIN                    |                         |   324K|    33M|  3138   (5)| 00:00:38 |       |       |
    |   2 |   BITMAP CONVERSION TO ROWIDS |                         |     3 |     9 |     1   (0)| 00:00:01 |       |       |
    |*  3 |    BITMAP INDEX FAST FULL SCAN| IDX_PS2_ACTION_TYPES    |       |       |            |          |       |       |
    |   4 |   PARTITION RANGE ITERATOR    |                         |   866K|    87M|  3121   (4)| 00:00:38 |   154 |   158 |
    |   5 |    TABLE ACCESS FULL          | PS2_FS_TRANSACTION_FACT |   866K|    87M|  3121   (4)| 00:00:38 |   154 |   158 |
    Predicate Information (identified by operation id):
       1 - access("AL1"."ACTION_TYPE_ID"="AL2"."ACTION_TYPE_ID")
       3 - filter("AL2"."ACTION_TYPE"='1' OR "AL2"."ACTION_TYPE"='2' OR "AL2"."ACTION_TYPE"='S')
    Thank you very much,
    Seyed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Case Statement in Analytic Function SUM(n) OVER(PARTITION BY x)

    Hi Guys,
    I have the following SQL that doesn't seem to consider the When clause I am using in the case staement inside the analytic function(SUM). Could somebody let me know why? and suggest the solution?
    Select SUM(Case When (A.Flag = 'B' and B.Status != 'C') Then (NVL(A.Amount_Cr, 0) - (NVL(A.Amount_Dr,0))) Else 0 End) OVER (PARTITION BY A.Period_Year) Annual_amount
         , A.period_year
         , B.status
    , A.Flag
    from A, B, C
    where A.period_year = 2006
    and C.Account = '301010'
    --and B.STATUS != 'C'
    --and A.Flag = 'B'
    and A.Col_x = B.Col_x
    and A.Col_y = C.Col_y
    When I use this SQL, I get
    Annual_Amount Period_Year Status Flag
    5721017.5 --------- 2006 ---------- C -------- B
    5721017.5 --------- 2006 ---------- O -------- B
    5721017.5 --------- 2006 ---------- NULL ----- A
    And when I put the conditions in the where clause, I get
    Annual_Amount Period_Year Status Flag
    5721017.5 ---------- 2006 ---------- O -------- B

    Here are some scripts,
    create table testtable1 ( ColxID number(10), ColyID number(10) , Periodname varchar2(15), Flag varchar2(1), Periodyear number(15), debit number, credit number)
    insert into testtable1 values(1, 1000, 'JAN-06', 'A', 2006, 7555523.71, 7647668)
    insert into testtable1 values(2, 1001, 'FEB-06', 'B', 2006, 112710, 156047)
    insert into testtable1 values(3, 1002, 'MAR-06', 'A', 2006, 200.57, 22376.43)
    insert into testtable1 values(4, 1003, 'APR-06', 'B', 2006, 0, 53846)
    insert into testtable1 values(5, 1004, 'MAY-06', 'A', 2006, 6349227.19, 6650278.03)
    create table testtable2 ( ColxID number(10), Account number(10))
    insert into testtable2 values(1, 300100)
    insert into testtable2 values(2, 300200)
    insert into testtable2 values(3, 300300)
    insert into testtable2 values(4, 300400)
    insert into testtable2 values(5, 300500)
    create table apps.testtable3 ( ColyID number(10), Status varchar2(1))
    insert into testtable3 values(1000, 'C')
    insert into testtable3 values(1001, 'O')
    insert into testtable3 values(1002, 'C')
    My SQL:
    select t1.periodyear
         , SUM(Case When (t1.Flag = 'B' and t3.Status != 'C') Then (NVL(t1.credit, 0) - (NVL(t1.debit,0))) Else 0 End) OVER (PARTITION BY t1.PeriodYear)
         Annual_amount
         , t1.flag
         , t3.status
         , t2.account
    from testtable1 t1, testtable2 t2, testtable3 t3
    where t1.colxid = t2.colxid
    and t1.colyid = t3.colyid(+)
    --and t1.Flag = 'B' and t3.Status != 'C'
    Result:
    PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
    2006 ------------------ 43337 --------------- A ----------- C ---------- 300100
    2006 ------------------ 43337 --------------- B ----------- O ---------- 300200
    2006 ------------------ 43337 --------------- A ----------- C ---------- 300300
    2006 ------------------ 43337 --------------- B ------------ ----------- 300400
    2006 ------------------ 43337 --------------- A ------------ ----------- 300500
    With condition "t1.Flag = 'B' and t3.Status != 'C'" in where clause instead of in Case statement, Result is (which is desired)
    PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
    2006 ------------------ 43337 --------------- B ----------- O ---------- 300200

  • CASE Statement error in function -- Please help!

    Hi All,
    I created a function in my report.
    It has a SQL query similar to the one below. The query works fine in SQL plus.
    It has a CASE statement. I am getting error at line4 at the select statement. Error is: "Encountered symbol 'SELECT'....."
    Can we use CASE statements like this in reports that use SELECT statements for RETURN EXPRESSIONS. Do we have to do any special?
    Can someone help me out of this trouble?
    THanks in advance.
    SELECT PARENT_id,
         CASE WHEN EXISTS (SELECT PARENT_id FROM CHILD CH1 WHERE CH1.PARENT_id = PARENT.PARENT_id AND UPPER(CH1.description) LIKE '%ABC%') THEN
              (SELECT CH2.MOD_id FROM CHILD CH2 WHERE CH2.PARENT_id = PARENT.PARENT_id AND UPPER(CH2.description) LIKE '%ABC%')
         ELSE
              (SELECT MOD_id FROM
              (SELECT MOD_id,PARENT_id FROM CHILD CH3 ORDER BY started) MOD2 WHERE MOD2.PARENT_id = PARENT.PARENT_id AND ROWNUM = 1
         END
    ) MOD_ID
    FROM PARENT;

    take out the parentheses after the PARENT_ID and see
    like below
    SELECT parent_id,
           CASE
              WHEN EXISTS (
                     SELECT parent_id
                       FROM CHILD ch1
                      WHERE ch1.parent_id = PARENT.parent_id
                        AND UPPER (ch1.description) LIKE '%ABC%')
                 THEN (SELECT ch2.mod_id
                         FROM CHILD ch2
                        WHERE ch2.parent_id = PARENT.parent_id
                          AND UPPER (ch2.description) LIKE '%ABC%')
              ELSE (SELECT mod_id
                      FROM (SELECT   mod_id, parent_id
                                FROM CHILD ch3
                            ORDER BY started) mod2
                     WHERE mod2.parent_id = PARENT.parent_id AND ROWNUM = 1)
           END AS mod_id
      FROM PARENT;       

  • Can we give multiple select statements in one function in PL/SQL

    Hi All,
    I am new to the PL/SQL. Can you please help me with the following problem.
    I am cretaing a function in which I have to extract some fields from three tables and to handle three tables I am first extracting the primary key from one table(acting as a foreign key for other table) in a variable declared in declare section, then I am selecting the required fields from the other table by giving that variable name in Where condition. My code is attached as well.
    e.g
    Create or Replace function <function name>(arguments)
    Return return type
    AS
    a1 a%TYPE;
    b_new b%TYPE;
    n fn%TYPE
    Select a into a1 from table1 where b like b_new;
    Select fn into n from table2 where id like a1;
    return a1,n; (can we pass record like this?)
    end;

    Left's first look at the approach you use.. 2 SQL statements that can be done using a single SQL statement.
    Actually it is not as bad as some other code posted here where people go and write complex PL/SQL code to do what could have been done using a single SQL statement.
    There are a couple of golden rules in Oracle development. One of these is to 'Maximise SQL and Minimise PL/SQL'.
    Why take a value from one SQL statement into PL/SQL and then use that value in a second SQL statement?
    Rather do this:
    select
    fn into n
    from table2
    where id like (Select a from table1 where b like b_new);Also keep in mind that in PL/SQL the above SQL construct is only able to fetch a single row - look at the bold above. The variable N can only hold a single value. If that SQL SELECT returns more than one value, how is variable N suppose to hold it?
    I suggest that you read [url http://www.oracle.com/pls/db102/to_toc?pathname=appdev.102%2Fb14261%2Ftoc.htm&remark=portal+%28Books%29]Oracle® Database PL/SQL User's Guide and Reference guide.

  • SQL Statement / index on function ??

    Hello
    My environment is : Oracle 9.2.0.7
    In "top sql sessions" I obtained that sql statement as below consumes many ressources.
    When I use "SQL Analyzer" ... no recommandation was specified but I wonder if an index on function may be use to optimize this request.
    I'd like to have your opinion on how to optimize this kind of request :
    SELECT trim(CARD_NUMBER) as CARD_NUMBER,
    trim(CUSTOMER.CLIENTS.CUSTOMER_ID) as CUSTOMER_ID,
    trim(LASTNAME) as LASTNAME,
    trim(FIRSTNAME) as FIRSTNAME,
    trim(EMAIL) as EMAIL,
    FROM CUSTOMER.CARTES, CUSTOMER.CLIENTS
    WHERE CUSTOMER.CARTES.CUSTOMER_ID = CUSTOMER.CLIENTS.CUSTOMER_ID
    AND trim(CUSTOMER.CARTES.CARD_NUMBER) = '1234567890'
    AND (trim(CUSTOMER.CLIENTS.POST_CODE)='12345')
    Plan execution is :
    SQL STATEMENT :
    JOIN
    TABLE ACCESS (FULL) CUSTOMER.CARTES
    TABLE ACCESS (FULL) CUSTOMER.CLIENTS
    Many thanks for any help.
    Regards,
    Guillaume

    AND trim(CUSTOMER.CARTES.CARD_NUMBER) =
    '1234567890'
    AND (trim(CUSTOMER.CLIENTS.POST_CODE)='12345')Yea function based index on trim(CUSTOMER.CARTES.CARD_NUMBER) and trim(CUSTOMER.CLIENTS.POST_CODE) might help.
    BUT I suggest to correct data insertion app and insert already trimmed data in your table to avoid such ugly queries.
    Gints Plivna
    http://www.gplivna.eu

  • Passing parameter into select statement by using function in discoverer

    I have created two functions in database named Period_in and Period_out and a global variable  g_period_name
    I have called Period_out function in VIEW(Select statement where condition).
    I have registered Period_in function in discoverer admin then created calculation (called Period_in(:input parameter))in discoverer plus.
    My expectation is user will enter period name and that will hit Period_in function and returns 1 and stores entered period name in g_period_name at runtime. then VIEW will executed and fetches data.
    But i am getting no data found.
    Problem is 2 functions running at the same time in select statement. Please help me to overcome this. Thanks in advance
    FUNCTION period_in (p_period VARCHAR2)
          RETURN NUMBER
       AS
       BEGIN
          g_period_name := p_period;
          RETURN 1;
       END period_in;
       FUNCTION period_out
          RETURN VARCHAR2
       AS
       BEGIN
          RETURN g_period_name;
       END period_out;

    You can use this code: 
    WITH cte
    AS ( SELECT EmpID ,
    EmpName ,
    [dbo].[udf_testFunction](EmpID) AS testfunctionvalue
    FROM #Temp
    SELECT EmpID ,
    EmpName ,
    testfunctionvalue ,
    testfunctionvalue * EmpID ,
    testfunctionvalue + 2
    FROM cte
    But using scalar functions in select clause can hurt the performance. Please see this link: 
    SQL Server Scalar User Defined Function Performance
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • Prepared Statements and Oracle functions:

    Consider this code:
    String searchText = "someInputText";
    StringBuffer sqlstmt = new StringBuffer();
    sqlstmt.append("SELECT ID_FIELD FROM ");
    sqlstmt.append("MY_TABLE WHERE NAME_FIELD ");
    sqlstmt.append("like INITCAP('%" + searchText + %')");
    PreparedStatement ps = con.prepareStatement(sqlstmt.toString());This works fine like this, but when I replace the searchText in the sqlstmt to ? it doesn't work:
    sqlstmt.append("like INITCAP('?')");
    PreparedStatement ps = con.prepareStatement(sqlstmt.toString());
    ps.setString(1, "%" + searchText + "%");How do you use the PreparedStatement with a
    function like INITCAP where you need to use a
    dynamic ? in the sql statement?
    Thanks,
    Rob.

    Very easy to miss this.
    Don't put the percentages IN the SQL statement.
    Append the percentages to your string.
    Like this:
    String searchText = "%" + "someInputText" + "%";
    StringBuffer sqlstmt = new StringBuffer();
    sqlstmt.append("SELECT ID_FIELD FROM ")
           .append("MY_TABLE WHERE NAME_FIELD ")
           .append("like INITCAP(?)");
    PreparedStatement ps = con.prepareStatement(sqlstmt.toString());
    ps.setString(1, searchText);
    resultSet = ps.executeQuery();Wish I saw this earlier for you.

  • Auto Stats Collection on function based indexes

    In 10g does AUTO Stats Collection job in the default weeknight / weekend window collect stats on "function based indexes".
    Thank You
    Message was edited by:
    user449511
    I got the reply in another similar post posted by me some time earlier.
    Thank You
    Message was edited by:
    user449511

    SELECT job_name, comments
    FROM dba_scheduler_jobs;Then refine your search using the columns in the view.

  • Insert statement with loop function

    Hello all,
    I'm new with the loop function
    What need to do is to use a select statement with a condition
    This output needs to be inserted in a table
    The values of the condition are stored also in a table
    It will be something like this:
    BEGIN
      FOR i IN (select nrs from table1)  LOOP
        INSERT INTO table_out_loop
        SELECT * FROM bigtable_vw
        WHERE nr = i
      END LOOP ;
    END ;
    I cant use a direct insert_into function in this case so I need the plsql to 'look' for the values 1 by 1 from the table1
    Any help would be appreciated

    Can't you just:
        insert into table_out_loop
        select *
        from   bigtable_vw
        where  nr in (select nrs from table1);
    If not, then post a better example and/or rephrase the question...

  • How should I pass complicated sql statements to a function ?

    Hello
    Some built-in functions, such as dbms_advisor.quicktune accepts sql statements as in parameters. Those parameters are treated as varchar2, but if the sql statement is complicated and contain " ' " characters then its hard to pass those params, Sometimes they arent parsed correctly.
    How should I pass a complicated statement (with subqueries, strings and so) to a function ?
    Thanks
    Guy

    user11973359 wrote:
    Hello
    Some built-in functions, such as dbms_advisor.quicktune accepts sql statements as in parameters. Those parameters are treated as varchar2, but if the sql statement is complicated and contain " ' " characters then its hard to pass those params, Sometimes they arent parsed correctly.
    How should I pass a complicated statement (with subqueries, strings and so) to a function ?
    Thanks
    GuyWhats your db verzion. To over come the single quotes issue in string you can use q'[]' representation of string.
    select q'[Karthick's]' from dual

  • Turn a case statement into a function

    I have a case statement (from an earlier post - thank you) that works. I was wondering if it could be edited and change into a function instead. I think it would be cleaner. The variable is set in the Form Properties (pCounterA).
    switch (pCounterA.value)
        case "1":
        profileA__1image.rawValue = profileA_1image.value.image.value;
        pCounterA.value = "2";
        break;
        case "2":
        profileA__1image.rawValue = profileA_2image.value.image.value;
        pCounterA.value = "3";
        break;
        case "3":
        profileA__1image.rawValue = profileA_3image.value.image.value;
        pCounterA.value = "4";
        break;
        case "4":
        profileA__1image.rawValue = profileA_4image.value.image.value;
        pCounterA.value = "5";
        break;
        case "5":
        profileA__1image.rawValue = profileA_5image.value.image.value;
        pCounterA.value = "1"; // loops back to the first image
        break;

    Hi,
    If you insert a script object by right clicking on the root container (often "form1"). It will appear unnamed in the root / variables in the hierarchy.
    First of all you should name the script object, staying away from reserved names, eg "this". Say "myScripts"
    Script objects can only contain Javascript, so you would need to convert FormCalc scripts (not an issue in your case).
    When you go into the script object, you start off a function with "function" followed by its name and inputs in brackets. The extent of the function is given by curly brackets:
    function changeImage(vCounter)
         switch (vCounter)
             case "1":
             profileA__1image.rawValue = profileA_1image.value.image.value;
             pCounterA.value = "2";
             break;
         } // close switch statement
    } // close function
    Back in the form you can call the function by referencing the name of the script object and the name of the function.
    myScripts.changeImage(pCounterA.value);
    A couple of things to note:
    The input in the script can refer to an objects value or a global variable, but in the function you can assign it s different name. So above the input pCounterA.value is EQUAL to vCounter in the function;
    You can have several inputs in the call for the function separated by commas;
    Don't have the same name for the script object AND the function
    Hope that helps,
    Niall

Maybe you are looking for