Case statement 'when IN cursor'

Hi folks.
I am wondering if it is possible to use the IN command within a CASE statement?
I am trying to see if a parameter falls under certain dates in another table. I have a cursor declared which points at that column of dates, and my case statement is like so
case parameter_date when IN certain_dates then if_holiday := 1 else if_holiday := 2 end;
It doesn't like it when I try to compile. And my procedure is listed as being Invalid.
Thanks for any help :)

I am wondering if it is possible to use the IN command within a CASE statement?Yes.
SQL> select dname
  2         , case when deptno in ( select deptno from emp )
  3                then 'Has staff' else 'empty' end
  4  from dept
  5  /
DNAME          CASEWHEND
ACCOUNTING     Has staff
RESEARCH       Has staff
SALES          Has staff
OPERATIONS     empty
SQL>What we can't do is use PL/SQL cursors like this
case parameter_date when IN certain_dates then if_holiday := 1 else if_holiday := 2 end;
                            ^^^^^^^^^^^^^They're not variables. At least, not that sort of variable.
Cheers, APC
blog: http://radiofreetooting.blogspot.com

Similar Messages

  • Is it possible to use a case statement when joining different tables based on input parameters?

    Hi,
    I have a scenario where my stored procedure takes 5 parameters and the users can pass NULL or some value to these parameters and based on the parameters, I need to pull data from various tables.
    Is it possible to use a case statement in the join, similar the one in the below example. I'm getting error when I use the below type of statement.
    select a.*
    from a
    case
    when parameter1=1 then
    inner join a on a.id = b.id
    when parameter1=2 then
    inner join a on a.id = c.id
    end;
    Please let me know, if this type of statement works, and if it works will it create any performance issues?. If the above doesn't work, could you please give me some alternate solutions?
    Thanks.

    Here's a technique for joining A to B or C depending on the input parameters. In theory, you are joining to both tables but the execution plan includes filters to skip whichever join is not appropriate. The drawback is that you have to do outer joins, not inner ones.
    CREATE TABLE A AS SELECT LEVEL ak FROM dual CONNECT BY LEVEL <= 100;
    CREATE TABLE b AS SELECT ak, bk
    FROM A, (SELECT LEVEL bk FROM dual CONNECT BY LEVEL <= 10);
    CREATE TABLE c(ak, ck) AS SELECT ak, bk*10 FROM b;
    variable p1 NUMBER;
    variable p2 NUMBER;
    exec :p1 := 1;
    exec :p2 := 20;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.01 |       7 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |
    |*  5 |     FILTER            |                 |      1 |        |      9 |00:00:00.01 |       4 |
    |*  6 |      TABLE ACCESS FULL| B               |      1 |      9 |      9 |00:00:00.01 |       4 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |
    |*  8 |    FILTER             |                 |      1 |        |      0 |00:00:00.01 |       0 |
    |*  9 |     TABLE ACCESS FULL | C               |      0 |      9 |      0 |00:00:00.01 |       0 |
    Predicate Information (identified by operation id):
       1 - access("A"."AK"="ITEM_0")
       2 - access("A"."AK"="ITEM_1")
       3 - filter("A"."AK"<=9)
      5 - filter(:P1 IS NOT NULL)
       6 - filter(("B"."AK"<=9 AND "B"."BK"=:P1))
       8 - filter((:P2 IS NOT NULL AND :P1 IS NULL))
       9 - filter(("C"."AK"<=9 AND "C"."CK"=:P2))
    You can see that table C was not really accessed: the buffer count is 0.
    exec :p1 := NULL;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    Now table B is not accessed.
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.02 |       7 |      2 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.02 |       7 |      2 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |*  5 |     FILTER            |                 |      1 |        |      0 |00:00:00.01 |       0 |      0 |
    |*  6 |      TABLE ACCESS FULL| B               |      0 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |
    |*  8 |    FILTER             |                 |      1 |        |      9 |00:00:00.01 |       4 |      2 |
    |*  9 |     TABLE ACCESS FULL | C               |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |

  • CURSOR and CASE STATEMENT

    Hello All:
    Is it possible to have the CASE Statement in the cursor? If so, could you please show me how to use it? I tried to use it as following but it did not work on Form Builder. I tried it on Oracle SQL *Plus and it worked there.
    CURSOR tbl_chck_cur IS
    SELECT chck_id,
    NVL(sup_chck_id,'') sup_chck_id,
    (CASE WHEN sup_chck_id = null THEN
    (SELECT order_no from tbl_chck_lk where tbl_chck.chck_id = tbl_chck_lk.chck_id ) ELSE
    (SELECT order_no from tbl_chck_lk
    where tbl_chck.chck_id = tbl_chck_lk.chck_id ) END) order_no,
    FROM tbl_chck;
    Thanks in advance for any help.
    KT

    First, get rid of that NVL on sup_chck_id. It does nothing. What do you want it to do, anyway???
    And what is the second table "Tbl_chk_sub" in the from clause?
    Ignoring tbl_chk_sub, this might work:SELECT T1.chck_id,
           T1.sup_chck_id,
           Decode(T1.sup_chck_id, null,LK1.order_no,Lk2.order_no) order_no
      FROM tbl_chck T1,
           tbl_chck_lk LK1,
           tbl_chck_lk LK2
      where LK1.chck_id(+)     = T1.chck_id
        and LK2.sup_chck_id(+) = T1.sup_chck_idIf the above does not work, you will have to find a work-around -- either do the lookup select in the post-query trigger, or create a stored function you can call from the select that returns the correct order_no based on the two columns, sup_chck_id and chck_id.
    Do you know if we can use the SELECT statement inside the CASE statement?Sometimes Forms are several steps behind in adapting new sql features. So it looks like you cannot at this time.

  • Creating view containing case statements received error ORA-22992

    We have a create view referencing table through dblink. The select statement in the create view has case statements, when running the Select statement alone, results are return. However, when executing the create view, it returns:
    SQL Error: ORA-22992: cannot use LOB locators selected from remote tables
    22992. 00000 - "cannot use LOB locators selected from remote tables"
    *Cause:    A remote LOB column cannot be referenced.
    *Action:   Remove references to LOBs in remote tables.
    One of the source table has LOB column but not in the select statement. The strange thing is when removing the case statement from the select, create view works fine. Can anybody tell me what caused the error and how to fix it?
    Create View Snippet:
    CREATE OR REPLACE VIEW "ABC"."XYZ" (....
    AS SELECT
    CASE
    WHEN A.OUTAGE =1
    THEN 'Y'
    ELSE 'N'
    END AS OUTAGE,
    FROM
    TABLEA@XXXX A
    LEFT JOIN TABLEB@XXXX B
    ON
    A.LOC =B.LO
    AND A.SITE =B.SITE
    WHERE
    A.CLASS ='CUSTOMER'
    AND A.PLUSSISGIS =1;

    What is your 4 digit Oracle version?
    Try rewriting the query to not use ANSI SQL92 joins. I found a link where this solved a problem similar to yours.
    DBLink problem ORA-22992
    >
    But, look at this curious thing: I re-write the query as follows:
    SELECT A.ID, A.ID_REF, A.EVENDATE, B.DESCRIPTION
    FROM A@ORCL A, B@ORCL B
    WHERE A.ID_REF = B.ID_REF;
    and it works fine... It seems like Oracle don't like the ANSI SQL92...
    >
    Several similar links by googling: 'SQL Error: ORA-22992'
    http://www.dbuggr.com/smallwei/solution-error-ora-22992-lob-locators-selected-remote-tabl/
    >
    Fixing ORA-22992 “cannot use LOB locators selected from remote tables” error
    You have migrated your Oracle 9i database to 10g and a distributed statement which worked fine in 9i now is getting error ORA-22992 “cannot use LOB locators selected from remote tables”. Even though the related remote table(s) does not contain any LOB column datatype.
    FIX:
    There is a bug on 9i,10g, and 11g that is related to this error. It is being fixed in 11.2. It can also be backported for previous 9i, 10g and 11g releases under the latest patchsets.
    You may also do a workaround as follow:
    Modify the affected SQL by adding the TO_CHAR function. For example:
    -- Original SQL:
    SELECT NVL2('a', 'b','c' ) FROM dual@remote_db;
    -- Modified SQL:
    SELECT TO_CHAR(NVL2('a','b','c')) FROM dual@remote_db;
    >
    See if that helps.

  • Help with multiple case statements

    Hello,
    I am new to BO.  I am on XI 3.0.  SQL 2005.  In Designer, I am trying to create a measure in a financial universe that would end up being multiple case statements within one select.  This is what I tried to do, but it doesn't work with the two case statements.  Can I use an ELSE leading into the second CASE WHEN somehow?  How can I accomplish this?  Sorry for my ignorance!
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 12 THEN dbo.ClientBudgetMonth.Stage1Sales END
    CASE WHEN  dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 11 THEN dbo.ClientBudgetMonth.Stage1Sales END
    Any Suggestions?
    Thanks,
    Holly

    Holly,
    I don't know enough about your data or requirement to provide a solution, however, the construct that you post will not work because it causes you to build an object with multiple case statements when only one case statement per object is permitted.  From what I see in your code I would be inclined to combine the two statements into one as such:
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month in (11,12) THEN dbo.ClientBudgetMonth.Stage1Sales else null END
    Thanks,
    John

  • Case Statement Help needed

    case
    when datepart(mm,[SDate]) between '9' and '11' and datepart(mm,[PDate] ) between '9' and '11'
    Then 'Q1_'
    when datepart(mm,[SDate]) between '12' and '02' and datepart(mm,[PDate] ) between '12' and '02'
    Then 'Q2_'
    when datepart(mm,[SDate]) between '03' and '05' and datepart(mm,[PDate] ) between '03' and '05'
    Then 'Q3_'
    when datepart(mm,[SDate]) between '06' and '08' and datepart(mm,[PDate] ) between '06' and '08'
    Then 'Q4_'
    else 'N/A' end as QTR
    from DDA_2015_FSR
    Datatype for SDate and Pdate
    2014-09-01 00:00:00
    I need help with above case statement, When I run the case statement I get 'N/A FSY_2015   ' When I add the following where clause to validate the results. In my table I do have records for all four quarters, Except Q1, all other rows I get  'N/A
    FSY_2015   '
    Am i missing something? Can someone help me here?
    where
    datepart(m,[SDate]) 
    between
    '12'
    and
    '02'
    and  
    datepart(m,[PDate]
    between
    '12'
    and
    '02'
    FM

    There is no CASE statement in SQL; it is a CASE expression. Big difference. 
    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
    The report period table gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Something_Report_Periods
    (something_report_name CHAR(10) NOT NULL PRIMARY KEY
       CHECK (something_report_name LIKE <pattern>),
     something_report_start_date DATE NOT NULL,
     something_report_end_date DATE NOT NULL,
      CONSTRAINT date_ordering
        CHECK (something_report_start_date <= something_report_end_date),
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • CASE statement falls straight  through to end

    Hello,
    I want the following code to execute a case statement when it hits todays day name. I know from the out put at the end that it is picking the name up but it wont act on the name in the case statement.
    This is my code,
    SQL> DECLARE num NUMBER;
      2  insert_rec VARCHAR2(150);
      3  party_id NUMBER;
      4  day_rec VARCHAR2(150);
      5  loop_max NUMBER;
      6  today VARCHAR2(20);
      7  yesterday VARCHAR2(20);
      8
      9  -- For debugging
    10  rec_count VARCHAR2(150);
    11
    12  BEGIN
    13    party_id := 3;
    14    loop_max := 7;
    15
    16    FOR loop_index IN 1 .. loop_max
    17    LOOP
    18
    19      EXECUTE IMMEDIATE 'SELECT MAX(SCH_ID) FROM FBT_SCHEDULE WHERE PAR_ID = ' || party_id || ''
    20      INTO num;
    21      -- For debugging
    22      -- rec_count := '... The last records party_id is ' || num;
    23      -- DBMS_OUTPUT.PUT_LINE(rec_count);
    24
    25      IF num IS NULL THEN
    26
    27        -- day_rec := sysdate;
    28        -- Find the start of the week for this period if the week starts on Sunday.
    29        -- For debugging
    30        -- DBMS_OUTPUT.PUT_LINE( 'select to_char(sysdate,'||''''||'DAY'||''''||') from dual');
    31        EXECUTE IMMEDIATE 'select to_char(sysdate,' || '''' || 'DAY' || '''' || ') from dual'
    32        INTO today;
    33        -- For debugging
    34        DBMS_OUTPUT.PUT_LINE(today);
    35
    36        day_rec :=
    37        CASE
    38        WHEN today = 'SUNDAY' THEN
    39          sysdate
    40        WHEN today = 'MONDAY' THEN
    41          sysdate -1
    42        WHEN today = 'TUESDAY' THEN
    43          sysdate -2
    44        WHEN today = 'WEDNESDAY' THEN
    45          sysdate -3
    46        WHEN today = 'THURSDAY' THEN
    47          sysdate -4
    48        WHEN today = 'FRIDAY' THEN
    49          sysdate -5
    50        WHEN today = 'SATURDAY' THEN
    51          sysdate -6
    52        END;
    53
    54        DBMS_OUTPUT.PUT_LINE('...The adjusted day is '||day_rec);
    55
    56        -- For debugging
    57        -- day_rec := '... The date is ' || day_rec;
    58        -- DBMS_OUTPUT.PUT_LINE(day_rec);
    59
    60        -- insert_rec := 'INSERT INTO FBT_SCHEDULE (PAR_ID, SCHEDULE_DATE) VALUES (''' || party_id || ''', TO_DATE(''' || day_rec || ''', ''' || 'dd / mon / rr' || '''' || '))';
    61        -- EXECUTE IMMEDIATE insert_rec;
    62
    63        ELSIF num > 0 THEN
    64
    65          EXECUTE IMMEDIATE 'SELECT SCHEDULE_DATE FROM FBT_SCHEDULE WHERE SCH_ID = ' || num || ''
    66          INTO day_rec;
    67
    68          day_rec := to_date(day_rec) + 1;
    69
    70          -- For debugging
    71          DBMS_OUTPUT.PUT_LINE(day_rec);
    72
    73          -- insert_rec := 'INSERT INTO FBT_SCHEDULE (PAR_ID, SCHEDULE_DATE) VALUES (''' || party_id || ''', TO_DATE(''' || day_rec || ''', ''' || 'dd / mon / rr' || '''' || '))';
    74          -- EXECUTE IMMEDIATE insert_rec;
    75
    76        END IF;
    77
    78      END LOOP;
    79    END;
    80  /
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    THURSDAY
    ...The adjusted day is
    PL/SQL procedure successfully completed.
    SQL>Thank You for any help
    Ben

    Ok, i looked at this a little harder and have some advice for you.
    1) lose the dynamic SQL or use binds if you NEED to be dynamic.
        EXECUTE IMMEDIATE 'SELECT MAX(SCH_ID) FROM FBT_SCHEDULE WHERE PAR_ID = ' || party_id || ''
        INTO num;
    should just be
    SELECT MAX(SCH_ID) INTO num FROM FBT_SCHEDULE WHERE PAR_ID = party_id;
          EXECUTE IMMEDIATE 'select to_char(sysdate,' || '''' || 'DAY' || '''' || ') from dual'
          INTO today;
    should just be
    today := to_char(sysdate, 'DAY');I'm also having a hard time following the logic, you have a party_id that doesn't change, yet you query based on that repeatedly inside your loop. It should be outside the loop.
    In all likelyhood, you could do this in no procedural code, something to strive for if you have spare cycles.
    Oh yeah, if you absolutely MUST use dynamic sql (you posted example code and my non-dynamic approach doesn't apply) then you MUST use bind variables.
            EXECUTE IMMEDIATE 'SELECT SCHEDULE_DATE FROM FBT_SCHEDULE WHERE SCH_ID = ' || num || ''
            INTO day_rec;
    would be
    EXECUTE IMMEDIATE 'SELECT SCHEDULE_DATE FROM FBT_SCHEDULE WHERE SCH_ID = :my_bind_variable' INTO day_rec USING num;

  • Error in writing the CASE statement

    i am writing these lines for my procedure getting error in writing CASE Statement when i remove case give result please any suggestion
    SELECT OTServicesMapping.ServiceId,Service_mst.Service_Name,
    OTServicesMapping.DependentOn,
    CASE OTROLEID -----error in this line
    WHEN (SELECT NVL(ChiefSurgeonServiceId,0) FROM ConfigOTService) = OTServicesMapping.ServiceId THEN 1
    else 0
    end,
    OTServicesMapping.OTPercent
    FROM Service_mst INNER JOIN
    OTServicesMapping ON Service_mst.Service_ID =OTServicesMapping.ServiceId LEFT OUTER JOIN
    Service_mst Service_mst_1 ON OTServicesMapping.DependentOn = Service_mst_1.Service_ID
    ERROR
    SQL Error: ORA-00905: missing keyword
    00905. 00000 - "missing keyword"
    *Cause:   
    *Action:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    What part does otroleid play in this problem? Why can't you say:
    CASE
         WHEN ( SELECT  NVL (ChiefSurgeonServiceId, 0)
                  FROM    ConfigOTService
              ) = OTServicesMapping.ServiceId  THEN 1
                                      ELSE 0
    END, ?
    Will there ever be more than 1 row in the ConfigOTService table? If so, you'll have a different error.
    Whenevder you have a problem, post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data. Explain how you get those results from that data.
    QAlways say what version of Oracle you're usiing.

  • Help with a CASE statement

    Please help me with a CASE Statement:
    - When ID = 15, 16, 17, 18 then "Bad"
    - when ID = 19, then "Average"
    - when ID = 21, then "Good"
    - else "Null"
    Thank you!!

    Well the 1st thing to do would be to correct my poor spelling... change    Delault : to Default :
    Don't know why you would get an error stating "The result of selection formula must be a boolean". It's working fine on my machine.
    If your ID field is numbers stored text you have a couple different options...
    1) Convert the ID to a number...
    Select  ToNumber({home.noone_ID})
    2) Wrap the ID values in double quotes...
       Case "15", "16", "17", "18" :
          "BAD"
    Even if this were your problem... the error should be something other than the boolean thing...
    Jason

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Invalid cursor state when trying to insert record

    Hi everyone!
    I'm using JDBC-ODBC bridge to connect to a mySql database, which works fine. Then I try to insert new records, but this only works for the first record in the table.
    When there is already a record in the table, I always get "[Microsoft][ODBC Driver Manager] Invalid cursor state" when calling the updateRow()-method of the result set.
    Here is my code:            // open db connection
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection conn = DriverManager.getConnection("jdbc:odbc:TTManager", "xxxx", "xxxx");
                // Prepare SQL statement
                java.sql.Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet result = stmt.executeQuery("SELECT * FROM Player");
                result.moveToInsertRow();Then all fields are filled in this manner:            result.updateString("Name", name);And finally the insertRow should be written to the db:            result.insertRow();But at this point it gives the mentioned error, including these messages:         at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5272)
            at sun.jdbc.odbc.JdbcOdbcResultSet.insertRow(JdbcOdbcResultSet.java:4132)Since I'm very unexperienced with Java, I guess (or hope^^) it's just some stupid beginner's mistake.
    Oh, almost forgot to mention: The new record's data doesn't violate any unique-constraints on the table, all fields are explicitely filled and all variable's data types are matching their according field types!
    Any help would be appreciated!
    reinski

    Ok, I needed to help myself and this is what I found out:
    If the table already contains records, it is not enough to doresult.moveToInsertRow();but I must beresult.last();
    result.moveToInsertRow();I didn't find any explanation and even the code examples from the Sun tutorial don't mention this, so I guess it's a bug occurring in my poor IT environment: DB server running mySQL 5.0.0-alpha on a P1-233-MMX w/ 64MB under WinNT4 (hey don't laugh!!^^).
    Maybe this information is of use to someone having similar problems...
    Greetings!
    reinski

  • Using case statement in merge when matched

    Hi,
    I want to use case statement in the when matched clause of merge statement to ensure that I update only those fields that are undated.
    create table TEST1
    NAME1 VARCHAR2(25),
    NAME2 VARCHAR2(25),
    ID NUMBER not null
    create table TEST2
    ID NUMBER not null,
    ID2 NUMBER not null,
    NAME1 VARCHAR2(25),
    NAME2 VARCHAR2(25)
    merge into test1 t1
    using
    test2 t2
    ON (t1.id = t2.id)
    when matched
    then
    case
    when t1.name1 != t2.name1
    then
    update set t1.name1 != t2.name1
    when t1.name2 != t2.name2
    then
    update set t1.name2 != t2.name2
    else
    null;
    end
    it does not work and raises invalid sql command. Any idea how can I do that?
    Thanks.
    Sajid
    Edited by: 808255 on Nov 12, 2010 4:22 AM

    Hi
    In that case you would have to use multiple statements and you may as well just use UPDATE instead of MERGE. Also, are you sure that you aren't trying to to fix a problem that doesn't actually exist.
    Think about where the execution time is going to come from...
    I would be tempted to do 1 UPDATE like this...
       UPDATE test1 t1
       SET    (t1.name1,
               t1.name2) = (SELECT  t2.name1,
                                    t2.name2
                            FROM    test2 t2
                            WHERE  t1.id = t2.id
                            AND   (t1.name1 != t2.name1
                             OR    t1.name2 != t2.name2))If you get specific performance issue with this, then post an explain plan and trace and I'll have a look.
    I don't this the cost of the update is going to be as great as you think.
    Cheers
    Ben

  • DoGet method is called 2 times when a switch-case statement is used

    Hello all,
    I have a servlet that, when run from browser, runs the doGet method 2 times.
    I have a switch case statement within the servlet and when I comment out this servlet, it runs 1 time as expected.
    Here is the code:
    public class RSSServlet extends HttpServlet {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            System.out.println("CALLED SERVLET");
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter out      = response.getWriter();
            DBQueriesRSS queries = new DBQueriesRSS();
            String queryType     = request.getParameter("queryType");
            String strCount      = request.getParameter("count");
            int count            = (strCount != null && !strCount.equalsIgnoreCase("null") && strCount.length() > 0) ?
                Integer.parseInt(strCount) : 25;
             if(queryType != null && !queryType.equalsIgnoreCase("null") && queryType.length() > 0) {
                System.out.println("IN IF STATEMENT");
                switch(Integer.parseInt(queryType)) {
                    case 1 : out.println(queries.getDefault(count));System.out.println("1");       break;
                    case 11: out.println(queries.getDefault(count));System.out.println("11");       break;
                    case 21: out.println(queries.getTopDaily(count));System.out.println("21");      break;
                    case 22: out.println(queries.getTopWeekly(count));System.out.println("22");     break;
                    case 23: out.println(queries.getTopMonthly(count));System.out.println("23");    break;
                    case 24: out.println(queries.getTopYearly(count));System.out.println("24");     break;
                    case 31: out.println(queries.getTopNDailyBW(count));System.out.println("31");   break;
                    case 32: out.println(queries.getTopNWeeklyBW(count));System.out.println("32");  break;
                    case 33: out.println(queries.getTopNMonthlyBW(count));System.out.println("33"); break;
                    case 34: out.println(queries.getTopNYearlyBW(count));System.out.println("34");  break;
                    default: out.println(queries.getTopWeekly(25));System.out.println("default");    break;
                System.out.println("OUT OF SWITCH");
            System.out.println("OUT OF IF");
            out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
           processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    } The results from running this servlet are:
    http://localhost/proxy/RSSServlet??queryType=34&count=66
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IF
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IFAnyone see anything obvious?
    TIA!

    in your case you want 'count' to be a class attribute rather than a local variable. But yes, incrementing it each time that the method is called will serve your purpose.

  • If statement in a cursor

    Hi
    I am trying to have a if statement inside a cursor clause. But it gives me error saying that "PLS-00103: Encountered the symbol "IF" when expecting one of the following: ( select <a SQL statement>". I know this is not the right syntax so is there any way that I can specify the table that the cursor should get its information from based on a if clause.
    The typeID field tells me which table to go to to get the information from. So if typeId=1 then go to table1 if it is type=2 then go to table2 etc.....
    CREATE OR REPLACE PROCEDURE FILLDATA(
         typeID IN NUMBER
    ) IS
    data varchar2(16);
    dataresult varchar2(16);
    cursor c1 is
            IF typeID=1 then
         select value from TableName#1
            ELSE
         select value from TableName#2
            END IF;
         where id='1';
    begin
         open c1;
         dataresult:='';
          loop
          fetch c1 into dataresult;
          EXIT WHEN c1%NOTFOUND;
             data:=concat(to_char(data), to_char(dataresult));
          end loop;
         close c1;
    end
    Your help will be really appreciated. Thanks a lot.
    Message was edited by:
    user561977
    Message was edited by:
    user561977
    Message was edited by:
    user561977

    Or I guess:
    DECLARE
        cur SYS_REFCURSOR;
    BEGIN
        CASE ROUND(DBMS_RANDOM.VALUE(1,2))
            WHEN 1 THEN OPEN cur FOR SELECT id FROM t1;
            WHEN 2 THEN OPEN cur FOR SELECT id FROM t2;
        END CASE;
        CLOSE cur;
    END;Also I can't think of a practical use for this here, but you can assign one ref cursor to another:
    DECLARE
        c1 SYS_REFCURSOR;
        c2 SYS_REFCURSOR;
        c_generic SYS_REFCURSOR;
    BEGIN
        CASE ROUND(DBMS_RANDOM.VALUE(1,2))
            WHEN 1 THEN
                DBMS_OUTPUT.PUT_LINE('Picked value: 1');
                OPEN c1 FOR SELECT id FROM t1;
                c_generic := c1;
            WHEN 2 THEN
                DBMS_OUTPUT.PUT_LINE('Picked value: 2');
                OPEN c2 FOR SELECT id FROM t2;
                c_generic := c2;
        END CASE;
        CLOSE c_generic;
        IF c1%ISOPEN THEN
            DBMS_OUTPUT.PUT_LINE('c1 is open.');
            CLOSE c1;
        ELSIF c2%ISOPEN THEN
            DBMS_OUTPUT.PUT_LINE('c2 is open.');
            CLOSE c2;
        ELSE
            DBMS_OUTPUT.PUT_LINE('It appears that neither c1 nor c2 is open.');
        END IF;
    END;
    Picked value: 2
    It appears that neither c1 nor c2 is open.
    PL/SQL procedure successfully completed.Message was edited by:
    William Robertson

  • Case statement problems in oracle forms 6i

    Hello,
    Any one can help me that how to use case statment in Oracle forms 6i.
    i have read one thread and there was no proper solution so could any one please let me know to use case statement.
    Please also let me know which category i should search for FORMS 6i.
    when i'm using below code with cursor then i'm getting error 103
    database:=11g
    application := forms 6i
    operating system:= win Xp
    code is given below :-
    cursor c1 is
    select nc.nomenclature_id,
    nvl(nc.category_value, 0) master,
    nvl(nc2.category_value, 0) case,
    nvl(nc3.category_value, 0) bundle,
    case
    when nvl(nc.category_value, 0) > 0 and
    nvl(nc2.category_value, 0) > 0 and
    nvl(nc3.category_value, 0) > 0 then
    'A' --All packouts Master, Case, Bundle
    when nvl(nc.category_value, 0) > 0 and
    nvl(nc2.category_value, 0) > 0 and
    nvl(nc3.category_value, 0) = 0 then
    'B' --Both Master and Case
    when nvl(nc2.category_value, 0) = 0 and
    nvl(nc3.category_value, 0) = 0 then
    'C' --Master Case Only
    else
    'N'
    end code
    from nomn_category nc, --master case
    (select nc2.nomenclature_id,
    nc2.category_value
    from nomn_category nc2
    where nc2.category_id = '230732') nc2,
    (select nc3.nomenclature_id,
    nc3.category_value
    from nomn_category nc3
    where nc3.category_id = '236566') nc3
    Edited by: Rahul on Feb 3, 2012 7:18 PM
    Edited by: Rahul on Feb 3, 2012 7:20 PM

    hello Andreas,
    It is ok but i dont have to use view there.
    i need to use without view, because this code has to be use in FORMS6i.
    But Forms6i doesn't support to case function. i'm newbie in Forms.
    If you can convert to below bold one portion(case) into decode then please help me or
    if you have any idea about Forms6i then please send me any link where is given explanation about excel report that how to make excel report through Forms6i step by step and that excel report should be generate on any dynamic path which is given by user:-
    cursor c1 is
    select nc.nomenclature_id,
    nvl(nc.category_value, 0) master,
    nvl(nc2.category_value, 0) case,
    nvl(nc3.category_value, 0) bundle,
    case
    when nvl(nc.category_value, 0) > 0 and
    nvl(nc2.category_value, 0) > 0 and
    nvl(nc3.category_value, 0) > 0 then
    *'A'*
    when nvl(nc.category_value, 0) > 0 and
    nvl(nc2.category_value, 0) > 0 and
    nvl(nc3.category_value, 0) = 0 then
    *'B' --Both Master and Case*
    when nvl(nc2.category_value, 0) = 0 and
    nvl(nc3.category_value, 0) = 0 then
    *'C'*
    else
    *'N'*
    end "code"
    from nomn_category nc,
    (select nc2.nomenclature_id,
    nc2.category_value
    from nomn_category nc2
    where nc2.category_id = '230732') nc2,
    (select nc3.nomenclature_id,
    nc3.category_value
    from nomn_category nc3
    where nc3.category_id = '236566') nc3
    thanks

Maybe you are looking for