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;

Similar Messages

  • CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL

    제품 : PL/SQL
    작성날짜 : 2001-11-13
    CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
    =======================================================
    PURPOSE
    아래의 자료는 Case 문에서 oracle 8.1.7과 Oracle 9i의 New Feature로 8.1.7에서는
    sqlplus 에서만 가능했고, 9i 부터는 pl/sql 까지 가능하다.
    Explanation
    1. Oracle 8.1.7 Feature
    Oracle 8.1.7 에서 Case 문은 Decode 문과 유사하지만, 기존의 decode 문을 쓰는 것보다
    더 많은 확장성과 Logical Power와 좋은 성능을 제공한다. 주로 나이와 같이 category 별로
    나눌때 주로 사용하고 Syntex는 아래와 같다.
    CASE WHEN <cond1> THEN <v1> WHEN <cond2> THEN <v2> ... [ELSE <vn+1> ] END
    각각의 WHEN...THEN 절의 argument 는 255 까지 가능하고 이 Limit를 해결하려면
    Oracle 8i Reference를 참조하면 된다.
    The maximum number of arguments in a CASE expression is 255, and each
    WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices,
    you can nest CASE expressions. That is expr1 can itself be a CASE expression.
    Case Example : 한 회사의 모든 종업원의 평균 봉급을 계산하는데 봉급이 $2000보다 작은경우
    2000으로 계산을 하는 방법이 pl/sql을 대신하여 case function을 사용할 수 있다.
    SELECT AVG(CASE when e.sal > 2000 THEN e.sal ELSE 2000 end) FROM emp e;
    Case Example : 나이를 column으로 가지고 있는 customer table을 예로 들어보자.
    SQL> SELECT
    2 SUM(CASE WHEN age BETWEEN 70 AND 79 THEN 1 ELSE 0 END) as "70-79",
    3 SUM(CASE WHEN age BETWEEN 80 AND 89 THEN 1 ELSE 0 END) as "80-89",
    4 SUM(CASE WHEN age BETWEEN 90 AND 99 THEN 1 ELSE 0 END) as "90-99",
    5 SUM(CASE WHEN age > 99 THEN 1 ELSE 0 END) as "100+"
    6 FROM customer;
    70-79 80-89 90-99 100+
    4 2 3 1
    1 SELECT
    2 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
    3 WHEN age BETWEEN 80 and 89 THEN '80-89'
    4 WHEN age BETWEEN 90 and 99 THEN '90-99'
    5 WHEN age > 99 THEN '100+' END) as age_group,
    6 COUNT(*) as age_count
    7 FROM customer
    8 GROUP BY
    9 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
    10 WHEN age BETWEEN 80 and 89 THEN '80-89'
    11 WHEN age BETWEEN 90 and 99 THEN '90-99'
    12* WHEN age > 99 THEN '100+' END)
    SQL> /
    AGE_G AGE_COUNT
    100+ 1
    70-79 4
    80-89 2
    90-99 3
    Example
    2. Oracle 9i Feature
    Oracle 9i부터는 pl/sql에서도 case문을 사용할 수 있으면 이것은
    복잡한 if-else 구문을 없애고, C언어의 switch문과 같은 기능을 한다.
    아래의 9i pl/sql Sample 및 제약 사항을 보면 아래와 같다.
    Sample 1:
    A simple example demonstrating the proper syntax for a case
    statement
    using a character variable as the selector. See the section entitled
    'Restrictions' at the end of this article for details on which PLSQL
    datatypes may appear as a selector in a case statement or
    expression.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    begin
    case achar
    when 'A' then dbms_output.put_line('The description was Excellent');
    when 'B' then dbms_output.put_line('The description was Very Good');
    when 'C' then dbms_output.put_line('The description was Good');
    when 'D' then dbms_output.put_line('The description was Fair');
    when 'F' then dbms_output.put_line('The description was Poor');
    else dbms_output.put_line('The description was No such Grade');
    end case;
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 2:
    A simple example demonstrating the proper syntax for a case
    expression
    using a character variable as the selector. See the section entitled
    'Restrictions' at the end of this article for details on which PLSQL
    datatypes may appear as a selector in a case statement or
    expression.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    description varchar2(20);
    begin
    description :=
    case achar
    when 'A' then 'Excellent'
    when 'B' then 'Very Good'
    when 'C' then 'Good'
    when 'D' then 'Fair'
    when 'F' then 'Poor'
    else 'No such grade'
    end;
    dbms_output.put_line('The description was ' || description);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    NOTE: The above simple samples demonstrate two subtle differences in the
    syntax
    required for case statements and expressions.
    1) A case STATEMENT is terminated using the 'end case' keywords; a
    case
    EXPRESSION is terminated using only the 'end' keyword.
    2) Each item in a case STATEMENT consists of one or more
    statements, each
    terminated by a semicolon. Each item in a case expression
    consists of
    exactly one expression, not terminated by a semicolon.
    Sample 3:
    Sample 1 demonstrates a simple case statement in which the selector
    is
    compared for equality with each item in the case statement body.
    PL/SQL
    also provides a 'searched' case statement as an alternative; rather
    than
    providing a selector and a list of values, each item in the body of
    the
    case statement provides its own predicate. This predicate can be any
    valid boolean expression, but only one case will be selected.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    begin
    case
    when achar = 'A' then dbms_output.put_line('The description was
    Excellent');
    when achar = 'B' then dbms_output.put_line('The description was Very
    Good');
    when achar = 'C' then dbms_output.put_line('The description was
    Good');
    when achar = 'D' then dbms_output.put_line('The description was
    Fair');
    when achar = 'F' then dbms_output.put_line('The description was
    Poor');
    else dbms_output.put_line('The description was No such Grade');
    end case;
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 4:
    This sample demonstrates the proper syntax for a case expression of
    the
    type discussed in Sample 3 above.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    description varchar2(20);
    begin
    description :=
    case
    when achar = 'A' then 'Excellent'
    when achar = 'B' then 'Very Good'
    when achar = 'C' then 'Good'
    when achar = 'D' then 'Fair'
    when achar = 'F' then 'Poor'
    else 'No such grade'
    end;
    dbms_output.put_line('The description was ' || description);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 5:
    This sample demonstrates the use of nested case statements. It is
    also
    permissable to nest case expressions within a case statement (though
    it
    is not demonstrated here), but nesting of case statements within a
    case
    expression is not possible since statements do not return any value.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    anum1 number := &anum1;
    anum2 number := &anum2;
    answer number;
    begin
    case anum1
    when 1 then case anum2
    when 1 then answer := 10;
    when 2 then answer := 20;
    when 3 then answer := 30;
    else answer := 999;
    end case;
    when 2 then case anum2
    when 1 then answer := 15;
    when 2 then answer := 25;
    when 3 then answer := 35;
    else answer := 777;
    end case;
    else answer := 555;
    end case;
    dbms_output.put_line('The answer is ' || answer);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 6:
    This sample demonstrates nesting of case expressions within another
    case
    expression. Note again the absence of semicolons to terminate both
    the
    nested case expression and the individual cases of those
    expressions.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    anum1 number := &anum1;
    anum2 number := &anum2;
    answer number;
    begin
    answer :=
    case anum1
    when 1 then case anum2
    when 1 then 10
    when 2 then 20
    when 3 then 30
    else 999
    end
    when 2 then case anum2
    when 1 then 15
    when 2 then 25
    when 3 then 35
    else 777
    end
    else 555
    end;
    dbms_output.put_line('The answer is ' || answer);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Although PL/SQL anonymous blocks have been used in all of the examples
    so far,
    case statements and expressions can also be used in procedures,
    functions, and
    packages with no changes to the syntax.
    The following samples are included for completeness and demonstrate the
    use of
    case statements and/or expressions in each of these scenarios.
    Sample 7:
    This sample demonstrates use of a case statement in a stored
    procedure.
    Note that this sample also demonstrates that it is possible for each
    of
    the items in the case body to consist of more than one statement.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace procedure testcasestmt ( anum IN number ) is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    end;
    exec testcasestmt(&anum);
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 8:
    This sample demonstrates the use of a case statement in a stored
    package.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace package testpkg2 is
    procedure testcasestmt ( anum IN number );
    function testcasestmt_f ( anum IN number ) return number;
    end testpkg2;
    create or replace package body testpkg2 is
    procedure testcasestmt ( anum IN number ) is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    end;
    function testcasestmt_f ( anum IN number ) return number is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    return anum;
    end;
    end testpkg2;
    exec testpkg2.testcasestmt(&anum);
    variable numout number
    exec :numout := testpkg2.testcasestmt_f(&anum);
    print numout
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 9:
    This sample demonstrates the use of a case expression in a stored
    package.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace package testpkg is
    procedure testcase ( anum IN number );
    function testcase_f ( anum IN number ) return number;
    end testpkg;
    create or replace package body testpkg is
    procedure testcase ( anum IN number ) is
    anumber number := anum;
    anothernum number;
    begin
    anothernum :=
    case
    when anumber = 1 then anumber + 1
    when anumber = 2 then anumber + 2
    when anumber = 3 then anumber + 3
    when anumber = 4 then anumber + 4
    when anumber = 5 then anumber + 5
    else 999
    end;
    dbms_output.put_line('The number was ' || anothernum);
    end;
    function testcase_f ( anum IN number ) return number is
    anumber number := anum;
    anothernum number;
    begin
    anothernum :=
    case
    when anumber = 1 then anumber + 1
    when anumber = 2 then anumber + 2
    when anumber = 3 then anumber + 3
    when anumber = 4 then anumber + 4
    when anumber = 5 then anumber + 5
    else 999
    end;
    dbms_output.put_line('The number was ' || anothernum);
    return anothernum;
    end;
    end testpkg;
    variable numout number
    exec testpkg.testcase(&anum);
    exec :numout := testpkg.testcase_f(&anum);
    print numout
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    제약 사항
    다음의 databasetype은 case 문에서 지원되지 않는다.
    BLOB
    BFILE
    VARRAY
    Nested Table
    PL/SQL Record
    PL/SQL Version 2 tables (index by tables)
    Object type (user-defined type)
    All of these types except for object types face a similar restriction
    even for if statements (i.e. they cannot be compared for equality directly) so this is unlikely to change for these types. Lack of support for object types is simply an implementation restriction which may be relaxed in future releases.
    Reference Ducumment
    Oracle 8.1.7 Manual
    NOTE:131557.1

    I have done the following code but doesn't
    like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
    I'm guessing it won't compile because you're trying to switch on a Button.
    I tried something
    like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
    Would appreciate it if someone could tell me how to position
    shapes using the graohic method. I think the problem is that you're confusing shapes with components.

  • Case, end case statement

    Hi all,
    name of my internal table is my_tab.i need to calculate the discounts depending upon the condition types(KSCHL) FROM KONV TABLE.
    WHEN KSCHL = ZDO1 calulation procedure is in percentage
                KSCHL= ZD02   calculation procedure is in fixed amount.
                and so on.....
    my_tab has fields
    my_tab-total
    my_tab-discount
    if kschl = ZD01, discount = my_tab-total - my_tab-discount
    if kschl = ZD02, discount =  my_tab-total * my_tab-discount/100.
    i wanted to know how to use this in CASE AND END CASE statement.
    regards
    akmal

    Hi akmal,
    chek out this code.
    Case kshcl.
    when 'ZD01'.
    discount = my_tab-total - my_tab-discount.
    when 'ZD02'.
    if kschl = ZD02, discount = my_tab-total * my_tab-discount/100.
    end case.
    if you ar looping through the internal table sthen  you can do the same af ter the when statements.
    regards,
    sateesh.

  • SQL CASE statement in XML template- End tag does not match start tag 'group

    Hi All,
    I am developing a report that has the SQL CASE statement in the query. I am trying to load this into RTF with report wizard and it gives me below error
    oracle.xml.parser.v2.XMLParseException: End tag does not match start tag 'group'
    Does XML publisher support CASE statement?
    My query is something like this
    SELECT customercode,
    SUM(CASE WHEN invoicedate >= current date - 30 days
    THEN balanceforward ELSE 0 END) AS "0-30",
    SUM(CASE WHEN invoicedate BETWEEN current date - 60 days
    AND current date - 31 days
    THEN balanceforward ELSE 0 END) AS "31-60",
    SUM(CASE WHEN invoicedate < current date - 60 days
    THEN balanceforward ELSE 0 END) AS "61>",
    SUM(balanceforward) AS total_outstanding
    FROM MyTable
    GROUP BY customercode
    ORDER BY total_outstanding DESC
    Please advice if the CASE statement or the double quotes are causing this error
    Thanks,
    PP

    I got this to work in the XML but the data is returning zeros for all the case statements. When I run this in toad I get results for all the case conditions but when ran in XML the data displayed is all zeros. I am not sure what I am missing. Can someone shed some light on this please
    Thanks!
    PP

  • Case Statement in Answers Filter

    Hi,
    I'm trying to build a query in Answers that filters the data returned based on the current month number. If the current month is 1 then we want to show all 12 months, otherwise we want to show months less than the current month. If I use the following:
    CASE WHEN extract(month from current_date) = 1 THEN "Calculated Values Monthly"."MONTH" >= 1 ELSE "Calculated Values Monthly"."MONTH" < extract (month from current_date) END
    I get the error below. All works fine until I add the CASE.
    Error Codes: YQCO4T56:OPR4ONWY:U9IM8TAC:OI2DL65P
    Location: saw.views.evc.activate, saw.httpserver.processrequest, saw.rpc.server.responder, saw.rpc.server, saw.rpc.server.handleConnection, saw.rpc.server.dispatch, saw.threadpool, saw.threadpool, saw.threads
    Odbc driver returned an error (SQLExecDirectW).
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 27002] Near <>=>: Syntax error [nQSError: 26012] . (HY000)
    Can you use a case statement in a filter? If not, what are the other options, if any?
    Thx

    ziekc wrote:
    Hi,
    I'm trying to build a query in Answers that filters the data returned based on the current month number. If the current month is 1 then we want to show all 12 months, otherwise we want to show months less than the current month. If I use the following:
    CASE WHEN extract(month from current_date) = 1 THEN "Calculated Values Monthly"."MONTH" >= 1 ELSE "Calculated Values Monthly"."MONTH" < extract (month from current_date) END
    I get the error below. All works fine until I add the CASE.
    Error Codes: YQCO4T56:OPR4ONWY:U9IM8TAC:OI2DL65P
    Location: saw.views.evc.activate, saw.httpserver.processrequest, saw.rpc.server.responder, saw.rpc.server, saw.rpc.server.handleConnection, saw.rpc.server.dispatch, saw.threadpool, saw.threadpool, saw.threads
    Odbc driver returned an error (SQLExecDirectW).
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 27002] Near <>=>: Syntax error [nQSError: 26012] . (HY000)
    Can you use a case statement in a filter? If not, what are the other options, if any?
    ThxAccording to your requirements, when the month is January, you want all 12 months; any other number and you want months from 1 to "1 less than the current month number." Yes? Okay, here's what to do:
    In the filter on your date column, click on the filter button, convert it to SQL and enter this:
    MONTH(tablename.date_column) BETWEEN 1 AND CASE WHEN MONTH(CURRENT_DATE) = 1 THEN 12 ELSE MONTH(CURRENT_DATE)-1 END
    Here's the logic:
    a) When the current month is January, then the case statement will yield 12 and the filter will be:
    WHERE MONTH(tablename.date_column) BETWEEN 1 AND 12 ...or all 12 months.
    b) When the current month is any other month, say June, then the case statement will yield one less than the what the month number is, or in this case 5.
    WHERE MONTH(tablename.date_column BETWEEN 1 AND 5 ...or all the months from 1 to 5 (Jan through May)
    This will give you what you want...

  • Can anyone suggest a select case statement in place of my if statements?

    I am having a little trouble switching my if statements to select case. Any help would be appreciated
    Option Strict On
    Option Explicit On
    Public Class Form1
    Private Player1 As String
    Private Player2 As String
    Private Player1Wins As Integer = 1
    Private Player2Wins As Integer = 1
    Private Tie As Integer = 1
    ' Close the program
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()
    End Sub
    ' ask for players names
    Private Sub frmMainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Player1 = InputBox("Enter Player 1's Name: ")
    lblPlayer1.Text = (Player1 + "'s Score:")
    Player2 = InputBox("Enter Player 2's Name:")
    lblPlayer2.Text = (Player2 + "'s Score:")
    End Sub
    Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
    ' game of rolling dice
    Dim randGen As New Random
    Dim intNum1 As Integer
    Dim intNum2 As Integer
    Dim intNum3 As Integer
    Dim intNum4 As Integer
    Dim intTotal As Integer
    Dim intTotal2 As Integer
    ' make random integer from 1 through 6
    intNum1 = randGen.Next(1, 7)
    intNum2 = randGen.Next(1, 7)
    intNum3 = randGen.Next(1, 7)
    intNum4 = randGen.Next(1, 7)
    ' display the right image in picDie1
    Select Case intNum1
    Case 1
    picDie1.Image = picOneDot.Image
    Case 2
    picDie1.Image = picTwoDots.Image
    Case 3
    picDie1.Image = picThreeDots.Image
    Case 4
    picDie1.Image = picFourDots.Image
    Case 5
    picDie1.Image = picFiveDots.Image
    Case 6
    picDie1.Image = picSixDots.Image
    End Select
    ' display the right image in picDie2
    Select Case intNum2
    Case 1
    picDie2.Image = picOneDot.Image
    Case 2
    picDie2.Image = picTwoDots.Image
    Case 3
    picDie2.Image = picThreeDots.Image
    Case 4
    picDie2.Image = picFourDots.Image
    Case 5
    picDie2.Image = picFiveDots.Image
    Case 6
    picDie2.Image = picSixDots.Image
    End Select
    ' display the right image in picDie3
    Select Case intNum3
    Case 1
    picDie3.Image = picOneDot.Image
    Case 2
    picDie3.Image = picTwoDots.Image
    Case 3
    picDie3.Image = picThreeDots.Image
    Case 4
    picDie3.Image = picFourDots.Image
    Case 5
    picDie3.Image = picFiveDots.Image
    Case 6
    picDie3.Image = picSixDots.Image
    End Select
    ' display the right image in picDie4
    Select Case intNum4
    Case 1
    picDie4.Image = picOneDot.Image
    Case 2
    picDie4.Image = picTwoDots.Image
    Case 3
    picDie4.Image = picThreeDots.Image
    Case 4
    picDie4.Image = picFourDots.Image
    Case 5
    picDie4.Image = picFiveDots.Image
    Case 6
    picDie4.Image = picSixDots.Image
    End Select
    ' calculate and display total number of dots
    intTotal = intNum1 + intNum2
    lblTotal.Text = intTotal.ToString()
    intTotal2 = intNum3 + intNum4
    lblTotal2.Text = intTotal2.ToString()
    ' display the winner
    If intTotal > intTotal2 Then
    MessageBox.Show("Player1 Wins")
    End If
    If intTotal2 > intTotal Then
    MessageBox.Show("Player2Wins")
    End If
    If intTotal = intTotal2 Then
    MessageBox.Show("Tie")
    End If
    ' display summary information when checkbox is checked
    If CheckBox1.Checked = True And
    intTotal > intTotal2 Then
    lblWins.Text = CStr(Player1Wins)
    Player1Wins = Player1Wins + 1
    lblScores.Visible = True
    End If
    If CheckBox1.Checked = True And
    intTotal2 > intTotal Then
    lblWins2.Text = CStr(Player2Wins)
    Player2Wins = Player2Wins + 1
    lblScores.Visible = True
    End If
    If CheckBox1.Checked = True And
    intTotal = intTotal2 Then
    lblTies.Text = CStr(Tie)
    Tie = Tie + 1
    lblScores.Visible = True
    End If
    End Sub
    End Class

    Put everything into lists. Here is elementary sample to get you started.
    Private lofDotImage As New List(Of Image)
    Private randGen As New Random
    Private picDie() As PictureBox
    Private Sub setup()
    ReDim picDie(3)
    picDie(0).Location = New Point()
    picDie(0).Size = New Size()
    picDie(1).Location = New Point()
    picDie(1).Size = New Size()
    picDie(2).Location = New Point()
    picDie(2).Size = New Size()
    picDie(3).Location = New Point()
    picDie(3).Size = New Size()
    For _delta As Integer = 0 To 3
    picDie(_delta).Visible = True
    Me.controls.add(picDie(_delta))
    Next _delta
    Dim _dice1 As Image = Nothing
    Dim _dice2 As Image = Nothing
    Dim _dice3 As Image = Nothing
    Dim _dice4 As Image = Nothing
    Dim _dice5 As Image = Nothing
    Dim _dice6 As Image = Nothing
    lofDotImage.Add(_dice1)
    lofDotImage.Add(_dice2)
    lofDotImage.Add(_dice3)
    lofDotImage.Add(_dice4)
    lofDotImage.Add(_dice5)
    lofDotImage.Add(_dice6)
    End Sub
    Private Sub roll()
    Dim _lofRolls As New List(Of Integer)
    Dim intScorePlayer1 As Integer = 0
    Dim intScorePlayer2 As Integer = 0
    For _delta As Integer = 0 To 3
    _lofRolls.Add(randGen.Next(1, 7))
    If _delta < 2 Then
    intScorePlayer1 += _lofRolls(_delta)
    Else
    intScorePlayer2 += _lofRolls(_delta)
    End If
    picDie(_delta).Image = lofDotImage(_lofRolls(_delta))
    Next _delta
    If intScorePlayer1 = intScorePlayer2 Then
    MessageBox.Show("Tie")
    ElseIf intScorePlayer1 > intScorePlayer2 Then
    MessageBox.Show("Player1 Wins")
    Else
    MessageBox.Show("Player2 Wins")
    End If
    End Sub
    Edit: Also to get better random, seed the random once and generate many times, the more seed is the less random.
    Also another tip: When comparing it is easy to check  = and <> compared to < or > in my experience, also for only one possible outcome use one main if block instead of many.

  • 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

  • CASE statement in SQL Server

    I am working on a project for ambulance response times. In
    the following query which is in my coldfusion code, I am using a
    CASE statement on a subquery to count the ambulance response times
    in bins. An ambulance should arrive at an emergency incident in
    less than 8:59 (539 seconds) or else it is considered late. In my
    coldfusion Transact-SQL code I am:
    1.) doing a subquery.
    2.) counting the 'event numbers' based on the time it took
    for the ambulance to arrive.
    3.) only counting Lee County ambulances and excluding A6 type
    calls (non-emergencies).
    4.) grouping it by the dateparts.
    SELECT DATENAME("M", I.I_tTimeDispatch) as mths,
    (DATEPART("yyyy", I.I_tTimeDispatch)) AS yr,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) BETWEEN 0 AND 539 THEN evnt END) AS OnTime,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) BETWEEN 540 AND 1028 THEN evnt END) AS Late,
    COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
    I.I_tTimeArrival)) > 1028 THEN evnt END) AS Outlier
    FROM (SELECT I_EventNumber AS evnt, I_tTimeDispatch,
    I_tTimeArrival, I_kTypeInfo, I_Agency FROM dbo.IIncident) as I
    INNER JOIN dbo.ITypeInfo AS T ON I.I_kTypeInfo =
    T.ITI_TypeInfo_PK
    WHERE I.I_Agency='LC'
    AND T.ITI_TypeID NOT LIKE 'A6*'
    GROUP BY (DATEPART("M", I.I_tTimeDispatch)), (DATENAME("M",
    I.I_tTimeDispatch)), (DATEPART("yyyy", I.I_tTimeDispatch))
    ORDER BY (DATEPART("yyyy", I.I_tTimeDispatch)) ASC,
    (DATEPART("M", I.I_tTimeDispatch)) ASC
    Here is my problem!
    I go into Microsoft Access to verify my statistics and I get
    different counts. For instance, in April 2008 my coldfusion query
    returns 3,944 on-time ambulance responses. My Access query for the
    same time period using only Lee County ambulances and excluding A6
    non-emergencies returns only 3,805 responses. This is an undercount
    of 139 responses. Even for my other time bins I am getting an
    undercount.
    Here is my Access SQL for the on time response bin (<539
    seconds or 8:59):
    SELECT Count(dbo_IIncident.I_EventNumber) AS
    CountOfI_EventNumber
    FROM dbo_IIncident INNER JOIN dbo_ITypeInfo ON
    dbo_IIncident.I_kTypeInfo = dbo_ITypeInfo.ITI_TypeInfo_PK
    WHERE (((dbo_IIncident.I_Agency)="lc") AND
    ((dbo_ITypeInfo.ITI_TypeID) Not Like "a6*") AND
    ((dbo_IIncident.I_tTimeDispatch) Between #4/1/2008# And #5/1/2008#)
    AND
    ((DateDiff("s",[dbo_IIncident]![I_tTimeDispatch],[dbo_IIncident]![I_tTimeArrival]))
    Between 0 And 539));
    How could two queries that are supposed to be doing the same
    thing return such different results?
    To clear up any confusion I am temporarily posting the page.
    Please look at it because it may help you visualize the problem.
    http://lcfcfn01/Secure/GTandLT_8_59.cfm

    Thank you for your quick reply.
    I thought about that, but it isn't what is causing the
    discrepancy in the numbers. This is because Access is hitting the
    SQL Server through ODBC. The time stamps in SQL Server are ODBC
    datetime stamps so they look like this: 4/19/2008 6:20:18 PM
    When my query uses the date #5/1/2008# it is like saying May
    1, 2008 00:00:00. Please correct me if I am wrong. The query won't
    return any results from May 1, 2008 because it stops at zero
    hundred hours. I believe it will only go to April 30, 2008 23:59:59
    and then stop there.
    I do try and play with the date ranges and the 'seconds'
    (<539 or >539) parameter and I consistently get different
    results from what my coldfusion page is telling me.
    David

  • [8i] Case statement generates ORA-00932: inconsistent datatypes

    Note: I am working with an 8i database (yes, it is quite old), and in this situation, I have to deal with the datatypes (i.e. CHAR), I am given to work with.
    I am attempting to calculate the amount of time product waits between manufacturing steps. As I've discovered though, sometimes I get a negative value when subtracting the date the previous step completes from the date the current step starts. As it is generally impossible to start a later step before an earlier step (imagine trying to screw a cap onto a bottle that doesn't have threads cut yet--it just can't happen), what I've found is that sometimes two steps are started on the same day and finished on the same day (though not necessarily the day they started). This situation CAN happen when one person did both steps and logged on to both steps at the same time, rather than logging on to one, then the other. So, what I need to do in these situations is replace the negative number with a zero (I'll treat the later step as having no wait time).
    Here is some sample data:
    (Note: the real data set is the result of a query, and has around 200K rows and more columns, but this should be representative enough to find a solution that works on my actual application.)
    CREATE TABLE     steps
    (     item_id          CHAR(25)
    ,     ord_nbr          CHAR(10)
    ,     sub_nbr          CHAR(3)
    ,     step_nbr     CHAR(4)
    ,     start_date     DATE
    ,     finish_date     DATE
    INSERT INTO steps
    VALUES ('A','0000000001','001','0010',TO_DATE('01/01/2011','mm/dd/yyyy'),TO_DATE('01/02/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('A','0000000001','001','0020',TO_DATE('01/01/2011','mm/dd/yyyy'),TO_DATE('01/02/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('A','0000000001','001','0030',TO_DATE('01/05/2011','mm/dd/yyyy'),TO_DATE('01/06/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('A','0000000001','002','0010',TO_DATE('01/01/2011','mm/dd/yyyy'),TO_DATE('01/02/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('A','0000000001','002','0020',TO_DATE('01/04/2011','mm/dd/yyyy'),TO_DATE('01/04/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('A','0000000001','002','0030',TO_DATE('01/06/2011','mm/dd/yyyy'),TO_DATE('01/07/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('B','0000000002','001','0005',TO_DATE('01/10/2011','mm/dd/yyyy'),TO_DATE('01/12/2011','mm/dd/yyyy'));
    INSERT INTO steps
    VALUES ('B','0000000002','001','0025',TO_DATE('01/10/2011','mm/dd/yyyy'),TO_DATE('01/12/2011','mm/dd/yyyy'));Here is the query I use that returns negative values sometimes:
    SELECT     item_id
    ,     ord_nbr
    ,     sub_nbr
    ,     step_nbr
    ,     start_date - last_step_finished
    FROM     (
         SELECT     s.*
         ,     LAG (s.finish_date)     OVER     (
                                  PARTITION BY     s.item_id
                                  ,          s.ord_nbr
                                  ,          s.sub_nbr
                                  ORDER BY     s.step_nbr
                                  )     AS last_step_finished
         FROM     steps s
    Returns:
    ITEM_ID                   ORD_NBR    SUB STEP START_DATE-LAST_STEP_FINISHED
    A                         0000000001 001 0010
    A                         0000000001 001 0020                        -1.000
    A                         0000000001 001 0030                         3.000
    A                         0000000001 002 0010
    A                         0000000001 002 0020                         2.000
    A                         0000000001 002 0030                         2.000
    B                         0000000002 001 0005
    B                         0000000002 001 0025                        -2.000These are the results I want to see:
    ITEM_ID                   ORD_NBR    SUB STEP START_DATE-LAST_STEP_FINISHED
    A                         0000000001 001 0010
    A                         0000000001 001 0020                         0.000
    A                         0000000001 001 0030                         3.000
    A                         0000000001 002 0010
    A                         0000000001 002 0020                         2.000
    A                         0000000001 002 0030                         2.000
    B                         0000000002 001 0005
    B                         0000000002 001 0025                         0.000And this is what I tried to do to get those results (comment notes what line generated the error):
    SELECT     item_id
    ,     ord_nbr
    ,     sub_nbr
    ,     step_nbr
    ,     CASE
              WHEN     start_dt - last_step_finished     < 0
              THEN     0
              ELSE     start_dt - last_step_finished  -- THIS LINE GENERATES THE ORA-00932 ERROR
         END                         AS days_in_queue
    FROM     (
         SELECT     s.*
         ,     LAG (s.finish_date)     OVER     ( PARTITION BY  s.item_id
                                    ,          s.ord_nbr
                                    ,          s.sub_nbr
                                    ORDER BY     s.step_nbr
                                  )     AS last_step_finished
         FROM     steps s
         );I know I've had inconsistent datatype errors before with case statements in this particular 8i database, but I can't seem to figure out why I'm getting one this time. I think it has something to do with the NULL values that can occur for last_step_finished. Also, if I change the case statement to:
    ,     CASE
              WHEN     start_dt - last_step_finished     < 0
              THEN     NULL
              ELSE     start_dt - last_step_finished  -- THIS LINE GENERATES THE ORA-00932 ERROR
         END     the query runs just fine. But, I don't want NULL, I want 0. In the next level of this query, I will be taking averages by item_id/step_nbr, and I want the 0's to be included in the average. (NULL values, as far as I can tell, would be excluded. AVG(NULL, 1, 2) =AVG (1,2) = 1.5 NOT AVG(0,1,2) = 1).
    Thanks in advance!

    Thanks, TO_NUMBER did the trick. Since you didn't state in your post where to use TO_NUMBER, here is my final solution, in case anyone in the future looks through this thread to find an answer to their question:
    SELECT     item_id
    ,     ord_nbr
    ,     sub_nbr
    ,     step_nbr
    ,     CASE
              WHEN     start_dt - last_step_finished     < 0
              THEN     0
              ELSE     TO_NUMBER(start_dt - last_step_finished)
         END                         AS days_in_queue
    FROM     (
         SELECT     s.*
         ,     LAG (s.finish_date)     OVER     ( PARTITION BY  s.item_id
                                    ,          s.ord_nbr
                                    ,          s.sub_nbr
                                    ORDER BY     s.step_nbr
                                  )     AS last_step_finished
         FROM     steps s
         );Edited by: user11033437 on Jun 27, 2011 11:17 AM
    I see you edited your post to add TO_NUMBER to it.

  • Question in Case Statement....

    Hi Gurus, I have a case statement as below: Here I have to get the Initials of person only where desc = underwriter. ( P.S sometimes there are multiple underwriter, thats why i put the min() around a character.)
    Initials =
    min(case when ( table1.DESC ) = 'UNDERWRITER' then table2.INITIALS when ( table1.DESC ) ='ASSIGN' then table2.INITIALS end )
    Please see data below:
    Underwriter Initials : SE
    -------------------------------XY
    Assign Initials : NR
    ----------------------------PQ
    Through my SQL I intend to get SE for Underwriter. But my SQL returns NR as it it is the minimum in the order. Any ideas please...........
    P.S: The Initials column is actually displayed in one of my reports; and the Initials column is dynamic; meaning ....i am prompting the User to select DESC values: Underwriter or Assign
    and based on that the prompt; the Initials Column should display either Underwriter Initials or Assign Initials.
    Thanks a lot.

    Hi Frank, thanks a lot for your reply. I am a lot closer to solving it now. A little more help please.
    The expected output is like below:
    1) Initials 2) Desc
    SE-------------- Underwriter
    NR---------------Assign
    Yes , i understand the whole purpose of case is to give different scnarios but in this case i have tried using something like:
    case when CR_ROLE_TYPE_DESC_REF.ROLE_TYP_DESC = :p_role_typ_desc then CR_PARTY_DIM.PARTY_NAME_INITIALS end
    but it gives me the wrong values. which i think is due to the Decode statement below:
    Please see the modified SQL:
    Here the user chooses prompts (DESC: Underwriter) and also pick a person name which has a decode for ASSIGN in it
    SELECT
    CR_ACCOUNT_DIM.ACCOUNT_NM,
    min(case when ( CR_ROLE_TYPE_DESC_REF.ROLE_TYP_DESC ) = 'UNDERWRITER' then CR_PARTY_DIM.PARTY_NAME_INITIALS when ( CR_ROLE_TYPE_DESC_REF.ROLE_TYP_DESC ) ='ASSIGN' then CR_PARTY_DIM.PARTY_NAME_INITIALS end)
    FROM
    CR_ACCOUNT_DIM,
    CR_CNSMR_RQST_PARTY_ROLE_RLSHP,
    CR_PARTY_DIM,
    CR_CONSUMER_RQST_DIM,
    CR_BUSINESS_SGMNT_REF,
    CR_CONSUMER_RQST_FACT
    WHERE
    ( CR_CONSUMER_RQST_FACT.CNSMR_RQST_DIM_PK_ID=CR_CONSUMER_RQST_DIM.CNSMR_RQST_DIM_PK_ID )
    AND ( CR_PARTY_DIM.PARTY_DIM_PK_ID= CR_CNSMR_RQST_PARTY_ROLE_RLSHP.PARTY_DIM_PK_ID )
    and
    decode(CR_CNSMR_RQST_PARTY_ROLE_RLSHP.ROLE_TYP_DESC,'ASSIGN',CR_PARTY_DIM.FIRST_NM || ' ' || CR_PARTY_DIM.MIDDLE_INTL || ' ' || CR_PARTY_DIM.LAST_NM ) = 'ROBERTO NIEL'
    Any ideas please....

  • Using Case statement to insert,update,delete  the tables

    Hi All,
    I have to check the databse ,
    if it is developement then
    insert/update/delete values in tables;
    if it staging then
    insert/update/delete values in tables;
    if it is production then
    insert/update/delete values in tables;
    thers is function available to check the current database
    For doing the about i am trying to write CASE statement like this
    SELECT function,
    case
    when fun = 'developement' then insert into table1 values ('abcd','1234')
    when fun = 'staging' then insert into table1 values ('abcd','1234')
    when fun= 'production' then insert into table1 values ('abcd','1234')
    else null
    from dual
    its throughing me an error
    please help
    Thanks,

    Hi,
    You can use CASE staement any place where an expression is expected.
    For example, in:
    UPDATE  table_a
    SET     col1 = exp1
    ,       col2 = exp2
    WHERE   exp3 = exp4;all the expressions are labled lke expn.
    Note that table_a, col1 and col2 are not expressions: you must hard-code these names, or use dynamic SQL.
    So it's okay to say:
    UPDATE  table_a
    SET     col1 = CASE
                       WHEN  db = 'development'  THEN  0
                       WHEN  db = 'staging'      THEN  1
                   END
    ,       col2 = CASE
                       WHEN  db = 'development'  THEN  NULL
                       WHEN  db = 'staging'      THEN  col2
                   END
    WHERE   db != 'production';In this example:
    in the development database, col1 is set to 0 and col2 is set to NULL
    in the staging database, col1 is set to 1 and col2 is unchanged (that is, set to what it already was)
    in the production database, nothing is changed (the WHERE condition is always FALSE)

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

  • 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

  • Issue with referencing Presentation variables(Date cols) in Case statement

    Hi,
    I m trying to reference presentation variables created on a Date column in the case statement of one of the request's columns as shown below:
    case when "- Quote Details"."Creation Date" between '@{from}{1999-1-1}' and '@{until}{2999-1-1}' then "- Quote Metrics"."# of Quotes" end
    I m getting a view display error with the below error message:
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1861, message: ORA-01861: literal does not match format string at OCI call OCIStmtExecute
    SQL Issued: SELECT "- Quote Types"."Level2 Name" saw_0, case when "- Quote Details"."Creation Date" between '4/1/2009' and '4/15/2009' then "- Quote Metrics"."# of Quotes" end saw_1 FROM "(Unity) Quotes Catalog" WHERE "- Quote Details"."Creation Date" BETWEEN timestamp '2009-04-01 00:00:00' AND timestamp '2009-04-15 00:00:00' ORDER BY saw_0
    When I created the prompt on the date field I put the following formula in the prompt:
    cast("- Time".Day as DATE)
    When I apply a filter on the request using these variables it works fine.
    If anyone has faced this kind of issue earlier and have a resolution, please help me out.
    Thanks,
    Kartik

    Thanks Goran!!
    I've created prompts by selecting columns from the logical tables (i.e. I've selected 2 different cols of datatype DATE...inorder to assign 2 presentation variables).
    Yes I m using calendar widget for prompts.
    I haven't included any filter in my report. I m trying to display a metric when it satisfies the case statement.
    I will defintley go through the blogs you mentioned for better understanding.
    Thanks,
    Kartik
    Query fired on physical db:
    WITH
    SAWITH0 AS (select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3,
    D1.c4 as c4,
    D1.c5 as c5
    from
    (select T192898.QLS_FIRST_ACAP_DT as c1,
    TO_DATE('3/2/2009','mm/dd/yyyy') as c2,
    TO_DATE('4/29/2009','mm/dd/yyyy') as c3,
    T188666.LEVEL2_NAME as c4,
    T188666.ID as c5,
    ROW_NUMBER() OVER (PARTITION BY T188666.ID, T192898.QLS_FIRST_ACAP_DT ORDER BY T188666.ID ASC, T192898.QLS_FIRST_ACAP_DT ASC) as c6
    from
    XXSLS_GBL_QTE_TYPES_V T188666,
    XXSLS_GBL_QTE_DTL_F T192898
    where ( T188666.ID = T192898.QUOTE_TYPE_ID )
    ) D1
    where ( D1.c6 = 1 ) ),
    SAWITH1 AS (select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3
    from
    (select count(distinct T192898.QUOTE_HEADER_ID) as c1,
    T188666.LEVEL2_NAME as c2,
    T188666.ID as c3,
    ROW_NUMBER() OVER (PARTITION BY T188666.ID ORDER BY T188666.ID ASC) as c4
    from
    XXSLS_GBL_QTE_TYPES_V T188666,
    XXSLS_GBL_QTE_DTL_F T192898
    where ( T188666.ID = T192898.QUOTE_TYPE_ID )
    group by T188666.ID, T188666.LEVEL2_NAME
    ) D1
    where ( D1.c4 = 1 ) ),
    SAWITH2 AS (select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3
    from
    (select case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end as c1,
    case when SAWITH0.c1 between SAWITH0.c2 and SAWITH0.c3 then SAWITH1.c1 else NULL end as c2,
    case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end as c3,
    ROW_NUMBER() OVER (PARTITION BY case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end , case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end ORDER BY case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end ASC, case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end ASC) as c4
    from
    SAWITH0 full outer join SAWITH1 On SAWITH0.c5 = SAWITH1.c3
    ) D1
    where ( D1.c4 = 1 ) )
    select SAWITH2.c1 as c1,
    SAWITH2.c2 as c2
    from
    SAWITH2
    order by c1

  • Oracle CASE statement logic

    Hi all,
    I have to compare the value of a varchar variable using a CASE statement and display the corresponding output.
    But when the following code is being executed, and i gave the value of dayrange as anything other than number, i am getting the error;
    The daysrange variable can be a number or a string (Hence i declared it as a varcahr2)
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    ORA-06512: at line 5
    06502. 00000 - "PL/SQL: numeric or value error%s"
    *Cause:   
    *Action:
    declare
    daysrange varchar2(10):='abc';
    x varchar2(100);
    begin
    CASE WHEN DAYSRANGE = 1 THEN x := 'LD';
              WHEN DAYSRANGE BETWEEN 2 AND 7 THEN x := 'LW';
              WHEN DAYSRANGE BETWEEN 8 AND 30 THEN x:= 'LM';
              WHEN DAYSRANGE BETWEEN 31 AND 90 THEN x:= 'L3M';
              WHEN DAYSRANGE BETWEEN 91 AND 180 THEN x:= 'L6M';
              WHEN DAYSRANGE BETWEEN 181 AND 365 THEN x:= 'LY';
              WHEN DAYSRANGE BETWEEN 366 AND 730 THEN x:= 'L2Y';
              WHEN DAYSRANGE > 730 THEN x:= 'O2Y';
         ELSE x:='x:= x';
         END case;--DATERANGE
    exception
    when case_not_found then
    x:='something';
    dbms_output.put_line(x);
    end;
    Edited by: Chaitanya on Nov 25, 2010 1:25 AM

    Hi,
    Chaitanya wrote:
    ... The daysrange variable can be a number or a string (Hence i declared it as a varcahr2)That's usually not a good design. It would be better to have two variables (or columns) if necessary, a VARCHAR2 and a NUMBER.
    If you can't change the design, then test daysrange, and then do different things depending on whether it is a number or not.
    For example:
    declare
         daysrange      varchar2(10)     := '17';
         daysrange_n     NUMBER;
         x           varchar2(100);
    begin
         IF  REGEXP_LIKE (daysrange, '^\d+$')
         THEN
              daysrange_n := TO_NUMBER (daysrange);
              x := CASE 
                   WHEN daysrange_n > 730     THEN 'O2Y'
                   WHEN daysrange_n > 365     THEN 'L2Y'
                   WHEN daysrange_n > 180     THEN 'L1Y'
                   WHEN daysrange_n >  90     THEN 'L6M'
                   WHEN daysrange_n >  30     THEN 'L3M'
                   WHEN daysrange_n >   7     THEN 'LM'
                   WHEN daysrange_n >   1     THEN 'LW'
                   WHEN daysrange_n =   1     THEN 'LD'
                                  ELSE  x          -- If necessary
                   END;
         END IF;
    ...The tests in a CASE expression are done in order. The n-th WHEN condition is tried only after conditions 1 through n have failed. That's why we can saY, for example,
    "daysrange_n > 365" instead of
    "daysrange_n BETWEEN 366 AND 730". If the 2nd test is even being performed, we know that the 1st test failed, and that daysrnage_n is not > 730.
    I'm not saying that you have to write CASE expressions like this, or that it's necessarily better. You should know that it's possible, then choose whichever way makes the most sense in this situation.

Maybe you are looking for

  • More than one class in single java source file?

    Is there a way to define more than one class in single java source file? I get a duplicate class definition error for each extra class, but I am sure there is a way to handle this in JDeveloper. Anyone knows how ?

  • Old VCR Video Tape to DVD

    Is there a way of taking old VCR videos (home movies) and transferring them to DVD? Can this be done from VCR to Mac computer?

  • How to use TRIM  DATA in CFFORM?

    How to use TRIM DATA in CFFORM? when data is retrieving from DATABASE. Wanna rtrim and ltrim while spaces.

  • Nokia E71 multiscanner re-installed but not workin...

    HI I JUST FORMATTED MY NOKIA E71. AS YOU ALL KNOW , THE MULTI SCANNER DOES NOT SHOW UP AFTER A FORMAT. BUT WITH THE HELP OF GUYS ON THE NOKIA DISCUSSION BOARD, I FOUND A SITE TO RE INSTALL MY MULTISCANNER APPLICATION. IT WORKED LIKE A CHARM. BUT NOW.

  • Any updates to the Travel Schema examples?

    Are there any examples that use the schema Travel, but use a business components interface instead of in-line coded SQL statements.