Decode Case statement to insert total text

Where the AGE BRACKET fields are empty or Null I need to insert "Total" text? Can anybody help?
Table
SOURCE CODE     AGE BRACKET     COUNT
CLUBBEN     0-40 Years     3     
CLUBBEN     41-49 Years     6     
CLUBBEN     50-59 Years     38     
CLUBBEN     60-69 Years     205     
CLUBBEN     70-79 Years     181     
CLUBBEN     80+ Years     19     
CLUBBEN          452     
CLUBJUNE     41-49 Years     2     
CLUBJUNE     50-59 Years     21     
CLUBJUNE     60-69 Years     100     
CLUBJUNE     80+ Years     1     
CLUBJUNE          124     
TOTAL          576     
Script Currently entered
SELECT DECODE(GROUPING(F.SOURCE_CODE),1,'TOTAL',0,F.SOURCE_CODE) as "SOURCE CODE",
CASE
WHEN D.AGE BETWEEN '0' AND '40' THEN '0-40 Years'
WHEN D.AGE BETWEEN '41' AND '49' THEN '41-49 Years'
WHEN D.AGE BETWEEN '50' AND '59' THEN '50-59 Years'
WHEN D.AGE BETWEEN '60' AND '69' THEN '60-69 Years'
WHEN D.AGE BETWEEN '70' AND '79' THEN '70-79 Years'
WHEN D.AGE >= '80' THEN '80+ Years'
ELSE ''
END AS"AGE BRACKET",
COUNT(F.MEMBER_COUNT) "COUNT"
FROM A3_FACT_NEW F, DIM_AGE D
WHERE F.AGE_KEY = D.AGE
AND F.JOIN_DATE BETWEEN '25/JUNE/2012' AND '30/AUGUST/2012'
AND F.BEN_TYPE = 'Prime member'
AND F.SOURCE_CODE IN ('CLUBBEN','CLUBJUNE')
GROUP BY ROLLUP(F.SOURCE_CODE,
CASE
WHEN D.AGE BETWEEN '0' AND '40' THEN '0-40 Years'
WHEN D.AGE BETWEEN '41' AND '49' THEN '41-49 Years'
WHEN D.AGE BETWEEN '50' AND '59' THEN '50-59 Years'
WHEN D.AGE BETWEEN '60' AND '69' THEN '60-69 Years'
WHEN D.AGE BETWEEN '70' AND '79' THEN '70-79 Years'
WHEN D.AGE >= '80' THEN '80+ Years'
ELSE ''
END)
ORDER BY(F.SOURCE_CODE),(2)
--------------------------------------------------------------------------------------------------------------

Welcome to the forum!!
Please consider the following when you post a question. This would help us help you better
1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
You can use the following query and do a copy past of the output.
select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
that are asked the answer is already there.
3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
I have the following table called sales
with sales
as
      select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
      union all
      select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
select *
  from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
For example in the above sales table, I want to know the total quantity and number of invoice for each product.
The output should look like this
Prod_id   sum_qty   count_inv
1         145       2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
use the {noformat}{noformat} tags.
The usage of the tag is like this.
<place your code here>\
7. If you are posting a *Performance Related Question*. Please read
   {thread:id=501834} and {thread:id=863295}.
   Following those guide will be very helpful.
8. Please keep in mind that this is a public forum. Here No question is URGENT.
   So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column

    Please Help!!!
    How to write a case statement for the totals column of two different years (2013 and 2014) of the same month so that I can get a +/- column.
                                      January 2014         January
    2013                            +/-
                    Region   Entry   Exit  Total    Entry   Exit   Total   (Total of Jan2014-Total of Jan2013)
                    A               2         3      
    40        5       7        30                    40-30= 10

    What is a table structure? Sorry cannot test it right now..
    SELECT <columns>,(SELECT Total FROM tbl WHERE Y=2014)-(SELECT Total FROM tbl WHERE Y=2013)
    FROM tbl
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

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

  • Use of decode/case statements

    I am trying to use a decode or case statement to check for a particular field code of 'SIP' and if that is the value I only want half of the production figure used in the calculations for that field ('SIP').
    The following code works well without the items commented out:
    SELECT ALL
    FINDER_WIS.PRODUCTION_HDR.END_TIME as prod_date,
    'SCD' as district,
    --decode(FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE,'SIP',FINDER_WIS.PRODUCTION_DATA.VOLUME/2,FINDER_WIS.PRODUCTION_DATA) AS TEST_SIP,
    /*case when FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE = 'SIP'
         then FINDER_WIS.PRODUCTION_DATA.VOLUME/2
              else FINDER_WIS.PRODUCTION_DATA.VOLUME
    end as fieldtest,*/
    round(SUM(NVL(FINDER_WIS.PRODUCTION_DATA.VOLUME,0))) as total_oil,
    ROUND(SUM(NVL(FINDER_WIS.PRODUCTION_DATA.VOLUME,0)) / TO_NUMBER(TO_CHAR(FINDER_WIS.PRODUCTION_HDR.END_TIME,'DD'))) AS BOPD
    FROM FINDER_WIS.PRODUCTION_HDR,
    FINDER_WIS.PRODUCTION_DATA,
    FINDER_WIS.FACILITY,
    FINDER_WIS.REPORTING_GROUP,
    FINDER_WIS.REPORTING_GROUP_DETAIL,
    FINDER_WIS.FACILITY_FIELD_X,
    SELECT distinct FINDER_WIS.FACILITY.FACILITY_S
    FROM FINDER_WIS.PRODUCTION_HDR,
    FINDER_WIS.PRODUCTION_DATA,
    FINDER_WIS.FACILITY,
    FINDER_WIS.REPORTING_GROUP,
    FINDER_WIS.REPORTING_GROUP_DETAIL
    WHERE (FINDER_WIS.PRODUCTION_HDR.ACTIVITY_TYPE = 'ALLOCATED'
    AND FINDER_WIS.PRODUCTION_HDR.TIME_PERIOD_TYPE = 'MONTH'
    AND FINDER_WIS.PRODUCTION_HDR.STATE_TYPE = 'STANDARD'
    AND FINDER_WIS.PRODUCTION_HDR.EXISTENCE_TYPE = 'ACTUAL'
    AND FINDER_WIS.PRODUCTION_DATA.MATERIAL_TYPE='OIL'
    and FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_TYPE = 'ASSET_TEAM'
    AND FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_ID ='SCD'
    and finder_wis.production_HDR.SOURCE = 'NEWWIS'
    AND FINDER_WIS.PRODUCTION_HDR.START_TIME BETWEEN :startdate_var AND :enddate_var)
    AND ((FINDER_WIS.PRODUCTION_DATA.PRODUCTION_HDR_S=FINDER_WIS.PRODUCTION_HDR.PRODUCTION_HDR_S)
    and (FINDER_WIS.PRODUCTION_HDR.FACILITY_S = FINDER_WIS.FACILITY.FACILITY_S)
    and (FINDER_WIS.PRODUCTION_HDR.START_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010')
    or FINDER_WIS.PRODUCTION_HDR.end_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010'))
    AND (FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_S = FINDER_WIS.REPORTING_GROUP_DETAIL.REPORTING_GROUP_S)
    AND (FINDER_WIS.FACILITY.FACILITY_S = FINDER_WIS.REPORTING_GROUP_DETAIL.FACILITY_S)))T
    WHERE (FINDER_WIS.PRODUCTION_HDR.ACTIVITY_TYPE = 'ALLOCATED'
    AND FINDER_WIS.PRODUCTION_HDR.TIME_PERIOD_TYPE = 'MONTH'
    AND FINDER_WIS.PRODUCTION_HDR.STATE_TYPE = 'STANDARD'
    AND FINDER_WIS.PRODUCTION_HDR.EXISTENCE_TYPE = 'ACTUAL'
    AND FINDER_WIS.PRODUCTION_DATA.MATERIAL_TYPE='OIL'
    and FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_TYPE = 'ASSET_TEAM'
    and finder_wis.production_HDR.SOURCE = 'NEWWIS'
    AND FINDER_WIS.PRODUCTION_HDR.START_TIME BETWEEN :startdate_var AND :enddate_var)
    AND ((FINDER_WIS.FACILITY.FACILITY_S = T.FACILITY_S)
    AND (FINDER_WIS.PRODUCTION_DATA.PRODUCTION_HDR_S=FINDER_WIS.PRODUCTION_HDR.PRODUCTION_HDR_S)
    AND FINDER_WIS.FACILITY_FIELD_X.UWI = FINDER_WIS.FACILITY.UWI
    AND FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE NOT IN ('MW','BRM','PLG','SIP')
    and (FINDER_WIS.PRODUCTION_HDR.FACILITY_S = FINDER_WIS.FACILITY.FACILITY_S)
    and (FINDER_WIS.PRODUCTION_HDR.START_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010')
    or FINDER_WIS.PRODUCTION_HDR.end_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010'))
    AND (FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_S = FINDER_WIS.REPORTING_GROUP_DETAIL.REPORTING_GROUP_S)
    AND (FINDER_WIS.FACILITY.FACILITY_S = FINDER_WIS.REPORTING_GROUP_DETAIL.FACILITY_S))
    GROUP BY FINDER_WIS.PRODUCTION_HDR.END_TIME
    the results look like this but this is without the values for the 'SIP' field:
    PROD_DATE     DISTRICT     TOTAL_OIL BOPD
    31/10/2007     SCD     168009     5420
    30/11/2007     SCD     167339     5578
    31/12/2007     SCD     170277     5493
    31/01/2008     SCD     173677     5602
    29/02/2008     SCD     168498     5810
    31/03/2008     SCD     172689     5571
    30/04/2008     SCD     168180     5606
    31/05/2008     SCD     165448     5337
    30/06/2008     SCD     164631     5488
    31/07/2008     SCD     170073     5486
    31/08/2008     SCD     166520     5372
    30/09/2008     SCD     160321     5344
    When I try to add the decode or case statement, I get ORA-00979; not a Group By expression as the error.
    Can anyone assist me with this please?
    Thanks in advance

    Hi and welcome to the forum.
    Simply put the field names you use in your DECODE also in your GROUP BY and it should work:
    simple example:
    MHO%xe> with t as (
      2  select 1 col1, 1 col2 from dual union all
      3  select 1 col1, 1 col2 from dual union all
      4  select 2 col1, 2 col2 from dual union all
      5  select 3 col1, 3 col2 from dual union all
      6  select 4 col1, 4 col2 from dual
      7  )
      8  select col1
      9  ,      decode(col1, 1, col2*100, col2)
    10  ,      sum(col2)
    11  from   t
    12  group by col1 -->> NO col2 here...
    13  order by col1;
    ,      decode(col1, 1, col2*100, col2)
    FOUT in regel 9:
    .ORA-00979: not a GROUP BY expression
    Verstreken: 00:00:05.78
    MHO%xe> with t as (
      2  select 1 col1, 1 col2 from dual union all
      3  select 1 col1, 1 col2 from dual union all
      4  select 2 col1, 2 col2 from dual union all
      5  select 3 col1, 3 col2 from dual union all
      6  select 4 col1, 4 col2 from dual
      7  )
      8  select col1
      9  ,      decode(col1, 1, col2*100, col2)
    10  ,      sum(col2)
    11  from   t
    12  group by col1, col2
    13  order by col1;
          COL1 DECODE(COL1,1,COL2*100,COL2)  SUM(COL2)
             1                          100          2
             2                            2          2
             3                            3          3
             4                            4          4

  • Nested Case Statement

    Hello,
    I need help implementing multiple Case Statements in a select statement. I can not get this to work in one statement.
    Select Statement
    select distinct
    allt.fk_jobcode_id as Job_Code,
    allt.fk_jobcode_descr as Classification,
    sum(allt.number_of_positions) as Number_Allotted,
    sum(number_of_positions) as Sum_Number_Allotted,
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,
    allt.fund_type as Fund
    from tbl_allotment allt, tbl_department dept, tbl_division div
    where isdeleted <> 'Y'
    and ALLT.FK_DEPARTMENT_ID = dept.department_id
    and ALLT.FK_DIVISION_ID = div.division_id
    group by fk_jobcode_id, fk_jobcode_descr, fund_type, department_name, division_name
    HAVING (count(fk_jobcode_descr ) = 1)
    order by Classification asc, Department_Division asc1st CASE Statement combines the Department_Name and Division_Name values but does not display the Division_Name if the value is 'N/A'.
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,value: Council Administrator's Office/Administration
    value: Council Administrator's Office/N/A will display as Council Administrator's Office
    I need to extend this now by using this CASE Statement, which displays the text 'Public Works' if the Department_Id = 00072.
         (CASE dept.department_id
         When '00072' then 'Public Works'
         Else dept.Department_Name
         End) as Department_Name, incorrect: Road Rehab Program/GLP Transportation Program Admin
    Should populate as: Public Works/GLP Transportation Program Admin
    select distinct
    allt.fk_jobcode_id as Job_Code,
    allt.fk_jobcode_descr as Classification,
    sum(allt.number_of_positions) as Number_Allotted,
    sum(number_of_positions) as Sum_Number_Allotted,
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,
      (CASE dept.department_id
         When '00072' then 'Public Works'
        ELSE dept.Department_Name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
           END),'/'||DIV.DIVISION_NAME||'',null)
      END) as Department_Name1,
    allt.fund_type as Fund
    from tbl_allotment allt, tbl_department dept, tbl_division div
    where isdeleted <> 'Y'
    and ALLT.FK_DEPARTMENT_ID = dept.department_id
    and ALLT.FK_DIVISION_ID = div.division_id
    group by fk_jobcode_id, fk_jobcode_descr, fund_type, department_name, division_name, department_id
    HAVING (count(fk_jobcode_descr ) = 1)
    order by Classification asc, Department_Division ascbut once I modify the select statement I am only getting value 'Public Works' for Department_Division value. Does not populate the Division_Name data. Does anyone know how to combine these CASE Statements? Thanks for reading this Thread also.

    Hi,
    I think you want something like this:
    SELECT       ...
    ,       CASE
               WHEN  department_id = '00072'
               THEN  'Public Works'
               ELSE  dept.department_name
           END
           ||
           CASE
               WHEN  div.division_name != 'N/A'
               THEN  '/' || div.division_name
           END          AS department_name1
    ...Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.

  • Decode/Case in Where clause

    Hello,
    We are experiencing an issue with a Select statement that uses Decode in the Where clause. Specifically, it seems to be ignoring a nested Decode and just returning the default value. We have another nested decode that works fine, though.
    A member of our team mentioned that he believed there was an issue with using Decode and Case statements inside of a where clause within HTML DB...Is this correct? If it is, is there a workaround? Since the nested Decode works elsewhere in this statement, that doesn't seem right.
    My select statement looks like:
    SELECT
       SUBSTR(OBOB.OBOB_CNAME, 0, 30) d,
       OBOB.OBOB_UID r
    FROM
       ISR_OBOB_OBJECT OBOB,
       ISR_OBAF_OBJECT_AFFILIATION OBAF,
       ISR.ISR_OBSD_SDR OBSD
    WHERE
       OBOB.OBOB_UID = OBSD.OBOB_UID AND
       OBOB.OBOB_UID = OBAF.OBOB_B_UID AND
    /*If Personal radio button is selected, displays all SDRs associated with user.
      If All is selected, displays all SDRs associated with IS group selected from drop down list
          or every SDR.
       OBAF.OBOB_A_UID = DECODE(:P1_DISPLAY_ALL,
                                       'Personal', :F101_APP_USER_UID,
    /*This is the decode statement that it seems to ignore. If ALL is selected, the query should see if a group has
        has been selected from a drop down list that appears when the ALL button is chosen. If a group is selected
        (the item isn't 0), only SDRs for that group should be shown. Otherwise, all SDRs for every group should display.
                                       'ALL', DECODE(:P1_SEARCH_IS_SUPPORT_GROUP, 0, OBAF.OBOB_A_UID, :P1_SEARCH_IS_SUPPORT_GROUP),
                                       OBAF.OBOB_A_UID) AND
    /*If Personal radio button is selected, display SDRs where user is the Primary assignee.
       OBAF.OBAT_UID = DECODE(:P1_DISPLAY_ALL, 'Personal', (select OBAT_UID from ISR_OBAT_OBJ_AFFIL_TYPE WHERE OBAT_APP_REF = 'SDR_PRIMARY'), OBAF.OBAT_UID) AND
    /*If a SDR Status (open, completed, on hold, not started...) is selected, only display the SDRs with that status.
       OBSD.KTTR_STATUS_UID = DECODE(:P1_ISR_STATUS_UID, 0, OBSD.KTTR_STATUS_UID, :P1_ISR_STATUS_UID) AND
    /*If SDR_History textbox is Null, or Open, Not Started, or On Hold SDR status has been selected, then all SDRs with
        a create date between today and 99999 months ago will display. Otherwise, only SDRs with a create date between
        today and however many months are in the textbox will display (i.e. Completed SDRs created in the past 6 months.)
       MONTHS_BETWEEN(sysdate, OBSD.OBSD_CREATE_DATE) <= DECODE(:P1_SDR_HISTORY, NULL, 99999, DECODE(:P1_ISR_STATUS_UID,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_OPEN'), 99999,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_NOT_STA'), 99999,
                                                              (select KTTR_UID from ISR_KTTR_TRANSLATION where KTTR_APP_REF = 'SD_STAT_HOLD'), 99999,
                                                              :P1_SDR_HISTORY))
    /*Alphabetical order
    Order by
       dWe originally wrote this as a PL/SQL statement that returned a query string since most of the where clause is dependent on items the user may or may not select, but we have moved the query into a multiselect list, which only seems to allow SQL Queries.
    Any help or advice would be appreciated.
    Thanks,
    Scott

    Scott: Did you try running that SQL statement in SQL Workshop in Apex? You can run it as it is, it will popup a window asking you to enter values for the bind variables.
    JAC73: I don't think an IN clause doesn't work that way, you need a actual SQL sub-query, not an expression from a DECODE/CASE statement. Search this site for str2tbl and see Tom's excellent discussion at
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:110612348061

  • Which is Faster among DECODE & CASE Statment.

    Can you please explain me the reason behind the fastest among DECODE & CASE statement?

    user13483989 wrote:
    Decode is have better performance.Because it is Oracle Inbuilt Function.So no neet to Specify Paraameters,It already contain Parameter.
    So Performance is good With decode.Please prove it with evidence, rather than just making supposed factual statements.
    From my tests, there's no clear difference one way or the other...
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_dummy      number;
      3    v_timestamp  timestamp;
      4    v_timestamp2 timestamp;
      5  begin
      6    v_timestamp := CURRENT_TIMESTAMP;
      7    dbms_output.put_line(v_timestamp);
      8    -- Test DECODE
      9    select count(*)
    10    into   v_dummy
    11    from   (select rownum rn from dual connect by rownum <= 1000000)
    12    where  decode(mod(rn,19),0,1,0) = 1;
    13    v_timestamp2 := CURRENT_TIMESTAMP;
    14    dbms_output.put_line(v_timestamp2);
    15    dbms_output.put_line('Decode Time Taken: '||(v_timestamp2 - v_timestamp) DAY TO SECOND);
    16    v_timestamp := CURRENT_TIMESTAMP;
    17    dbms_output.put_line(v_timestamp);
    18    -- Test CASE
    19    select count(*)
    20    into   v_dummy
    21    from   (select rownum rn from dual connect by rownum <= 1000000)
    22    where  case when mod(rn,19) = 0 then 1 else 0 end = 1;
    23    v_timestamp2 := CURRENT_TIMESTAMP;
    24    dbms_output.put_line(v_timestamp2);
    25    dbms_output.put_line('Case Time Taken:   '||(v_timestamp2 - v_timestamp) DAY TO SECOND);
    26* end;
    SQL> /
    18-JAN-11 12.01.58.856000
    18-JAN-11 12.02.00.653000
    Decode Time Taken: +000000000 00:00:01.797000000
    18-JAN-11 12.02.00.653000
    18-JAN-11 12.02.02.309000
    Case Time Taken:   +000000000 00:00:01.656000000
    PL/SQL procedure successfully completed.
    SQL> /
    18-JAN-11 12.02.03.668000
    18-JAN-11 12.02.05.403000
    Decode Time Taken: +000000000 00:00:01.735000000
    18-JAN-11 12.02.05.403000
    18-JAN-11 12.02.07.152000
    Case Time Taken:   +000000000 00:00:01.749000000
    PL/SQL procedure successfully completed.
    SQL> /
    18-JAN-11 12.02.07.871000
    18-JAN-11 12.02.09.777000
    Decode Time Taken: +000000000 00:00:01.906000000
    18-JAN-11 12.02.09.777000
    18-JAN-11 12.02.11.684000
    Case Time Taken:   +000000000 00:00:01.907000000
    PL/SQL procedure successfully completed.
    SQL> /
    18-JAN-11 12.02.15.324000
    18-JAN-11 12.02.17.090000
    Decode Time Taken: +000000000 00:00:01.766000000
    18-JAN-11 12.02.17.090000
    18-JAN-11 12.02.18.855000
    Case Time Taken:   +000000000 00:00:01.765000000
    PL/SQL procedure successfully completed.
    SQL>

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Regarding case statement and decode function

    Hi Experts,
    I have question.....regarding case statement and decode statement....
    Can you please explain me that which one will be efficient,to place in insert statement...
    insert statement(
    (case when ........then
                         case when ....then
                         else
                         end)
      else
    end)
    or
    insert statement(
    case when.....then
    decode(....)
    else
    end)
    Can you people explain me which one is more efficient method?
    Thanks in advance.......

    The are major differences to talk about in case of CASE vs DECODE, but performance wise both are pretty much the same.
    Have a look at Tom's thread
    Ask Tom &amp;quot;better performance - case or decode&amp;quot;
    I would suggest to use CASE whenever possible. Don't worry about the performance part.

  • Decode Statement Inside the Case statement

    Can we use Decode Statement inside a CASE Statement as show below --
    It is giving an error -- Is the a better way to write with out any error
    create or replace
    function test (a varchar2) RETURN VARCHAR2
    is
    m varchar2(20);
    begin
    m :=
    CASE
    WHEN a IN (
    '1009' -- (soon obsolete)
    ,'1010'
    ,'1019'
    ,'1051'
    ,'XGP'
    ,'XSC')
    THEN (SELECT DECODE(v_lef_cd,'NAM','71','GLB','99','01') into m FROM DUAL)
    -- ) THEN '01' -- UNITED STATES OF AMERICA
    WHEN a IN (
    '1069' -- South Africa
    ,'SAO' -- South Africa
    ,'SA' -- South Africa
    ) THEN '26' -- South Africa
    ELSE NULL
    END;
    return m;
    end;

    Hi,
    You can only use DECODE in SQL statements.
    Your SELECT DECODE (...) INTO statement would work anywhere a PL/SQL statement is allowed; but PL/SQL statements are not allowed within CASE expressions.
    Remember, the expression that comes after THEN in a CASE expression must be a single value.
    I would write a function like this using IF ... ELSIF statements. It's a little more typing than CASE, but a lot easier to code, test and maintain.
    If you want to use CASE, here's one way:
    ...     m := CASE
              WHEN  a  IN ('1069', 'SAO', 'SA')
                   THEN  '26'     -- South Africa
              WHEN  a  NOT IN ('1009', '1019', '1051', 'XGP', 'XSC')
              OR    a  IS NULL
                   THEN  NULL
              WHEN  v_lef_cd = 'NAM'
                   THEN  '71'
              WHEN  v_lef_cd = 'GLB'
                   THEN  '99'
                   ELSE  '01'     -- USA
              END;This assumes that you have a variable v_lef_cd defined.
    If you want, you can nest CASE expressions, like this:
    ...     m := CASE
              WHEN  a  IN ('1069', 'SAO', 'SA')
                   THEN  '26'     -- South Africa
              WHEN  a  IN ('1009', '1019', '1051', 'XGP', 'XSC')
                   THEN  CASE  v_lef_cd
                          WHEN  'NAM'
                             THEN  '71'
                          WHEN  'GLB'
                             THEN  '99'
                             ELSE  '01'     -- USA
                         END
              END;Always format your code, so you can see where the CASE expressions and each of the WHEN clauses begin and end.
    When posting formatted text on this site, type these 6 characters:
    (all small letters, inside curly brackets) before and after sections of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • SQL Expression in decode function or case statement?

    Can I put SQL expressions in decode function or case statement?
    For example,
    select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
    from element le;
    or
    select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
    ELSE 'Y'
    from element le;
    None of the above work.
    Can anyone tell me how to make it work?
    Is there any workaround?
    Thanks,
    J

    You simply needed and END to your CASE statement;
    SQL> with profile_data as (
       select 'XXXX_AFTER' name, 1 object_id from dual),
         element as (
       select 1 profile from dual union all
       select 2 from dual)
    select le.profile,
       case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
       THEN 'N'
       ELSE 'Y'
       END new_col
    from element le
       PROFILE N
             1 Y
             2 N

  • Use of case  in an insert statement...

    Hi ,
    i have an insert statement in a db packaged procedure which needs a case statement to be used.....
    I want to use the case in a statement like the following...
    insert into x(a,b,c,d,e)
    values(a,b,case b='1' then c_val , d_val , null else null , null , e_val);
    In other words when the b_value (b column) has value '1' (in the example above) then the values for c , d columns of the tables are those passed as parameters to the procedure . On the other hand , when the the b_value (b column) has not value '1' then the values for c , d columns of the tables should be null and the on the e column another value passed as parameter to the procedure....????
    Is the above general syntax of insert correct...????
    Many thanks,
    Simon

    Something like this could do the trick:
    insert into x
                (a, b, c, d, e)
         values (a,
                 b,
                 case
                    when b = '1'
                       then c_val
                 end,
                 case
                    when b = '1'
                       then d_val
                 end,
                 case
                    when b = '1'
                       then null
                    else e_val
                 end
                );

  • Decode and case statement in the update..

    Its is more to it, but I want to check with you guys, the experts on this, this look busy to me, it should be a more simplify way of doing it, do you think will work
    The government decide to change the ethnic codes, and we have to come with certain rules to in our report, anyway, do you think this will work? again It is more to it I declare my variables, this is just one part of the precedure.
    BEGIN
          UTL_FILE.fclose_all;
          v_file_handle := UTL_FILE.fopen (v_out_path, v_out_file, 'a');
          UTL_FILE.put_line (v_file_handle,
                             CHR (10) || TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS')
          UTL_FILE.put_line (v_file_handle, 'Entering  spbpers_update');
          SELECT upd_spbpers_upd_cur IS
              spriden_pidm,
              szscapp_birth_state,
              szscapp_birth_city,
              DECODE(szscapp_hisp_or_latino_ind,Y,'2',N,'1'),
              DECODE(szscapp_hisp_or_latino_options,XCM,'2',CUB,'2',MEX,'2',PRI,'2',XSM,'2',ESP,'2',XOH,'2'),  
              DECODE(szscapp_amer_indn_alaska_opt,XAN,'1','1',XCW,'1',XCH,'1',XCK,'1',XNV,'1',XSX,'1'),         
              DECODE(szscapp_amer_indn_alaska_other,XON,'1') (,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),  
              DECODE(szscapp_asian_options,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),   ,          
              DECODE(szscapp_other_east_asia,(IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),            
              DECODE(szscapp_other_indian_subcont,XIS,'1'),    
              DECODE(szscapp_other_southeast_asia,XSA,'1'),   
              DECODE(szscapp_blk_or_afr_amer_opt,XAA,'1',XAF,'1',XCB,'1',XOA,'1'),     
              DECODE(szscapp_blk_or_afr_amer_other,XOA,'1'),   
              DECODE(szscapp_natve_hawaian_options,GUM,'1',XHI,'1',ASM,'1',XOP,'1'), 
              DECODE(szscapp_hawaiian_other,XOP,'1'),             
              DECODE(szscapp_white_options,XEU,'1',XME,'1',XOW,'1'),           
              DECODE(szscapp_white_other(XOW,'1')
         FROM
             saturn_midd.szscapp 
         WHERE
         spriden_id =  szscapp_id
         AND  spriden_ntyp_code = 'CAPL'
       IF upd_spbpers_upd_cur%ISOPEN
          THEN
             CLOSE upd_spbpers_upd_cur;
          END IF;
          OPEN upd_spbpers_upd_cur;
          LOOP
             FETCH upd_spbpers_upd_cur
              INTO v_pidm,v_birth_state,v_birth_city,v_latino_ind,v_latino_options,
                   v_indn_alaska_opt,v_indn_alaska_other,v_asian_options,
                   v_other_east_asia,v_other_indian_subcont,v_other_southeast_asia,
                   v_blk_or_afr_amer_opt,v_blk_or_afr_amer_other,v_natve_hawaian_options,           
                   v_hawaiian_other,v_white_options,v_white_other;
             EXIT WHEN upd_spbpers_upd_cur%NOTFOUND; 
             IF upd_spbpers_upd_cur%FOUND
               UPDATE  saturn.spbpers
                           set SPBPERS_ETHN_CODE  = CASE
                   WHEN v_latino_ind            IS NOT NULL THEN (spbpers_ethn_code = v_latino_ind,spbpers_activity_date = sysdate)     
                   WHEN v_latino_options        IS NOT NULL THEN (spbpers_ethn_code = v_latino_options,spbpers_activity_date = sysdate)
                   WHEN v_indn_alaska_opt       IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_opt,spbpers_activity_date = sysdate)
                   WHEN v_indn_alaska_other     IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_other,spbpers_activity_date = sysdate)
                   WHEN v_asian_options         IS NOT NULL THEN (spbpers_ethn_code = v_asian_options,spbpers_activity_date = sysdate)
                   WHEN v_other_east_asia       IS NOT NULL THEN (spbpers_ethn_code = v_other_east_asia,spbpers_activity_date = sysdate)             
                   WHEN v_other_indian_subcont  IS NOT NULL THEN (spbpers_ethn_code = v_other_indian_subcont,spbpers_activity_date = sysdate)
                   WHEN v_other_southeast_asia  IS NOT NULL THEN (spbpers_ethn_code = v_other_southeast_asia,spbpers_activity_date = sysdate)
                   WHEN v_blk_or_afr_amer_opt   IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_opt,spbpers_activity_date = sysdate)
                   WHEN v_blk_or_afr_amer_other IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_other,spbpers_activity_date = sysdate)
                   WHEN v_natve_hawaian_options IS NOT NULL THEN (spbpers_ethn_code = v_natve_hawaian_options,spbpers_activity_date = sysdate)
                   WHEN v_hawaiian_other        IS NOT NULL THEN (spbpers_ethn_code = v_hawaiian_other,spbpers_activity_date = sysdate)
                   WHEN v_white_options         IS NOT NULL THEN (spbpers_ethn_code = v_white_options,spbpers_activity_date = sysdate)
                   WHEN v_white_other           IS NOT NULL THEN (spbpers_ethn_code = v_white_other,spbpers_activity_date = sysdate)
                   WHEN v_birth_state           IS NOT NULL THEN (spbpers_stat_code_birth = v_birth_state,spbpers_activity_date = sysdate)
                   WHEN v_birth_city            IS NOT NULL THEN (spbpers_city_birth = v_birth_city,spbpers_activity_date = sysdate)
                   WHERE spbpers_pidm = v_pidm;
                  END
                     END IF;
          END LOOP;

    Did the procedure compile ?
    Doesn't look like a right Decode syntax.
    DECODE (col1,'VAL1','This','VAL2','That','ElseThis')
    means
    --Psuedocode
    IF col1 = 'VAL1' THEN 'This'
    IF col1 = 'VAL2' THEN 'That'
    ELSE 'ElseThis'You can use CASE statement Instead of DECODE
    CASE
    when      szscapp_amer_indn_alaska_other
         in ('XON','IND','JPN','KOR','PAK' ..... )  THEN '1'
    when      szscapp_hisp_or_latino_options
         in ('XCM','CUB','MEX','PRI','XSM','ESP','XOH' ...) THEN '2'
    END  SS

  • Case statement insert not working

    This cursor is retrieving data for each pidm
    SPRIDEN_PIDM     ACTIVITY1     ACTIVITY2     ACTIVITY3     ACTIVITY4     ACTIVITY5     ACTIVITY6
    2287953                        RA      RC      RF     RJ       RN      RU
    CURSOR activities_cursor
          IS
             SELECT spriden_pidm,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   1
                                  ) activity1,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   2
                                  ) activity2,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   3
                                  ) activity3,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   4
                                  ) activity4,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   5
                                  ) activity5,
                    REGEXP_SUBSTR (szcasup_activities,
                                   '[[:alpha:]]+',
                                   1,
                                   6
                                  ) activity6              
               FROM saturn_midd.szcasup, saturn.spriden
              WHERE szcasup_common_appl_id = spriden_id
                AND spriden_ntyp_code = 'CAPP';Then I fetched the results in variadles
    FETCH activities_cursor
              INTO v_pidm, v_activity1, v_activity2, v_activity3, v_activity4,
                   v_activity5,v_activity6;
    Created a loop with a case statement
    LOOP
             FETCH activities_cursor
              INTO v_pidm, v_activity1, v_activity2, v_activity3, v_activity4,
                   v_activity5,v_activity6;
             EXIT WHEN activities_cursor%NOTFOUND;
             IF activities_cursor%FOUND
             THEN
                CASE
                   WHEN (v_activity1 IS NOT NULL)
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity1,
                                      sysdate
                    WHEN (v_activity2 IS NOT NULL)
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity2,
                                      sysdate
                   WHEN (v_activity3 IS NOT NULL)
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity3,
                                      sysdate
                    WHEN (v_activity4 IS NOT NULL)
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity4,
                                      sysdate
                END CASE;
             END IF;
          END LOOP;
    It is working just for one activity (activity1) The variable definition is correctv_activity1 sorints.sorints_ints_code%TYPE;
    v_activity2 sorints.sorints_ints_code%TYPE;
    v_activity3 sorints.sorints_ints_code%TYPE;
    v_activity4 sorints.sorints_ints_code%TYPE;
    v_activity5 sorints.sorints_ints_code%TYPE;
    v_activity6 sorints.sorints_ints_code%TYPE;
    Edited by: peace4all on Aug 16, 2009 9:42 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    peace4all wrote:
    It is working just for one activity (activity1) The variable definition is correct
    Well, what else did you expect? CASE evaluates brances starting first one. If WHEN condition is not met it continues to next one. As soon as WHEN condition is met, THEN clause is executed after that CASE exits. You need to use IF statement, not case:
    with t as (
               select to_date('01/11/2005','dd/mm/yyyy') Start_Date,to_date('13/11/2005','dd/mm/yyyy') End_Date,13 Days,'CMP1' Component,1000.00 Amount from dual union all
               select to_date('01/11/2005','dd/mm/yyyy'),to_date('13/11/2005','dd/mm/yyyy'),13,'CMP2',826.67 from dual union all
               select to_date('15/11/2005','dd/mm/yyyy'),to_date('20/11/2005','dd/mm/yyyy'),6,'CMP1',413.33 from dual union all
               select to_date('15/11/2005','dd/mm/yyyy'),to_date('20/11/2005','dd/mm/yyyy'),6,'CMP2',166.67 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP1',633.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP2',111.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP3',22.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP4',333.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP1',2480.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP2',1488.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP3',496.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP4',200.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2005','dd/mm/yyyy'),16,'CMP1',522.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2005','dd/mm/yyyy'),16,'CMP2',166.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2005','dd/mm/yyyy'),16,'CMP3',242.00 from dual
    SELECT  P_Month,
            SUM(LEAST(LAST_DAY(P_Month),end_date) - GREATEST(P_Month,start_date) + 1) Total_Days
      FROM  t,
             SELECT  ADD_MONTHS(first_month,LEVEL - 1) P_Month
               FROM  (
                      SELECT  TRUNC(MIN(start_date),'MM') first_month,
                              TRUNC(MAX(end_date),'MM') last_month
                        FROM  t
               CONNECT BY LEVEL <= MONTHS_BETWEEN(last_month,first_month) + 1
      WHERE P_Month BETWEEN TRUNC(start_date,'MM') and end_date
      GROUP BY P_Month
      ORDER BY P_Month
    with t as (
               select to_date('01/11/2005','dd/mm/yyyy') Start_Date,to_date('13/11/2005','dd/mm/yyyy') End_Date,13 Days,'CMP1' Component,1000.00 Amount from dual union all
               select to_date('01/11/2005','dd/mm/yyyy'),to_date('13/11/2005','dd/mm/yyyy'),13,'CMP2',826.67 from dual union all
               select to_date('15/11/2005','dd/mm/yyyy'),to_date('20/11/2005','dd/mm/yyyy'),6,'CMP1',413.33 from dual union all
               select to_date('15/11/2005','dd/mm/yyyy'),to_date('20/11/2005','dd/mm/yyyy'),6,'CMP2',166.67 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP1',633.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP2',111.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP3',22.00 from dual union all
               select to_date('21/11/2005','dd/mm/yyyy'),to_date('28/11/2005','dd/mm/yyyy'),8,'CMP4',333.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP1',2480.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP2',1488.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP3',496.00 from dual union all
               select to_date('01/12/2005','dd/mm/yyyy'),to_date('15/12/2005','dd/mm/yyyy'),15,'CMP4',200.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2005','dd/mm/yyyy'),16,'CMP1',522.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2005','dd/mm/yyyy'),16,'CMP2',166.00 from dual union all
               select to_date('16/12/2005','dd/mm/yyyy'),to_date('31/12/2006','dd/mm/yyyy'),381,'CMP3',242.00 from dual
    SELECT  P_Month,
            SUM(LEAST(LAST_DAY(P_Month),end_date) - GREATEST(P_Month,start_date) + 1) Total_Days
      FROM  t,
             SELECT  ADD_MONTHS(first_month,LEVEL - 1) P_Month
               FROM  (
                      SELECT  TRUNC(MIN(start_date),'MM') first_month,
                              TRUNC(MAX(end_date),'MM') last_month
                        FROM  t
               CONNECT BY LEVEL <= MONTHS_BETWEEN(last_month,first_month) + 1
      WHERE P_Month BETWEEN TRUNC(start_date,'MM') and end_date
      GROUP BY P_Month
      ORDER BY P_Month
    LOOP
             FETCH activities_cursor
              INTO v_pidm, v_activity1, v_activity2, v_activity3, v_activity4,
                   v_activity5,v_activity6;
             EXIT WHEN activities_cursor%NOTFOUND;
             IF v_activity1 IS NOT NULL
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity1,
                                      sysdate
              ELSIF v_activity2 IS NOT NULL
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity2,
                                      sysdate
              ELSIF v_activity3 IS NOT NULL
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity3,
                                      sysdate
              ELSIF v_activity4 IS NOT NULL
                   THEN
                      INSERT INTO saturn.sorints
                                  (sorints_pidm, sorints_ints_code,
                                   sorints_activity_date)
                                   values
                                    v_pidm,
                                     v_activity4,
                                      sysdate
              END IF;
          END LOOP;SY.

  • Case statement to decode

    Hello,
    I am used to using case within my select statements, I need to use decode if possible for this one. Its for a record group within in forms, and the case statement is not working. Could someone please help me write this with decode instead of case?
    SELECT CASE
           WHEN months_between(sysdate , c.birth_dt) BETWEEN 168 AND 216 THEN 1 --14 to 18
           WHEN months_between(sysdate , c.birth_dt) BETWEEN 217 AND 252 THEN 2 --18 to 21
           WHEN months_between(sysdate , c.birth_dt) BETWEEN 253 AND 780 THEN 3 --21 to 65
           WHEN months_between(sysdate , c.birth_dt) > 780 then 4 --older than 65
           ELSE NULL END
    FROM mw_clients cThanks in advance!
    Jim P.

    Below solution is very easy to write.
    But I think that performance will be bad.Not really as dual is internal to the SQL engine so there's little difference between the two...
    SQL> ed
    Wrote file afiedt.buf
      1  with mw_clients as (select add_months(sysdate,-200) as birth_dt from dual union
      2                      select add_months(sysdate,-220) from dual union
      3                      select add_months(sysdate,-400) from dual)
      4  -- END OF TEST DATA
      5  select 4+
      6         decode(Least(months_between(sysdate , c.birth_dt),168),
      7                168,decode(greatest(months_between(sysdate , c.birth_dt),216),
      8                           216,-3,0)
      9                ,0)+
    10         decode(Least(months_between(sysdate , c.birth_dt),217),
    11                217,decode(greatest(months_between(sysdate , c.birth_dt),252),
    12                           252,-2,0)
    13                ,0)+
    14         decode(Least(months_between(sysdate , c.birth_dt),253),
    15                253,decode(greatest(months_between(sysdate , c.birth_dt),780),
    16                           780,-1,0)
    17                ,0) as result
    18* from mw_clients c
    SQL> /
        RESULT
             3
             2
             1
    Elapsed: 00:00:00.01
    Execution Plan
    Plan hash value: 1277652150
    | Id  | Operation        | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT |      |     3 |    27 |     9  (34)| 00:00:01 |
    |   1 |  VIEW            |      |     3 |    27 |     9  (34)| 00:00:01 |
    |   2 |   SORT UNIQUE    |      |     3 |       |     9  (78)| 00:00:01 |
    |   3 |    UNION-ALL     |      |       |       |            |          |
    |   4 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |   5 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |   6 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
              0  consistent gets
              0  physical reads
              0  redo size
            456  bytes sent via SQL*Net to client
            396  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
              3  rows processed
    SQL>
    SQL> ed
    Wrote file afiedt.buf
      1  with mw_clients as (select add_months(sysdate,-200) as birth_dt from dual union
      2                      select add_months(sysdate,-220) from dual union
      3                      select add_months(sysdate,-400) from dual)
      4  -- END OF TEST DATA
      5  select c.birth_dt,
      6         (select 1 from dual where months_between(sysdate , c.birth_dt) BETWEEN 168 AND 216 union
      7          select 2 from dual where months_between(sysdate , c.birth_dt) BETWEEN 217 AND 252 union
      8          select 3 from dual where months_between(sysdate , c.birth_dt) BETWEEN 253 AND 780 union
      9          select 4 from dual where months_between(sysdate , c.birth_dt) > 780
    10         ) as result
    11* from mw_clients c
    SQL> /
    BIRTH_DT                RESULT
    06/08/1974 10:15:39          3
    06/08/1989 10:15:39          2
    06/04/1991 10:15:39          1
    Elapsed: 00:00:00.01
    Execution Plan
    Plan hash value: 706016619
    | Id  | Operation        | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT |      |     3 |    27 |     9  (34)| 00:00:01 |
    |   1 |  SORT UNIQUE     |      |     4 |       |    12  (84)| 00:00:01 |
    |   2 |   UNION-ALL      |      |       |       |            |          |
    |*  3 |    FILTER        |      |       |       |            |          |
    |   4 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |*  5 |    FILTER        |      |       |       |            |          |
    |   6 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |*  7 |    FILTER        |      |       |       |            |          |
    |   8 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |*  9 |    FILTER        |      |       |       |            |          |
    |  10 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |  11 |  VIEW            |      |     3 |    27 |     9  (34)| 00:00:01 |
    |  12 |   SORT UNIQUE    |      |     3 |       |     9  (78)| 00:00:01 |
    |  13 |    UNION-ALL     |      |       |       |            |          |
    |  14 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |  15 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    |  16 |     FAST DUAL    |      |     1 |       |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - filter(MONTHS_BETWEEN(SYSDATE@!,:B1)<=216 AND
                  MONTHS_BETWEEN(SYSDATE@!,:B2)>=168)
       5 - filter(MONTHS_BETWEEN(SYSDATE@!,:B1)<=252 AND
                  MONTHS_BETWEEN(SYSDATE@!,:B2)>=217)
       7 - filter(MONTHS_BETWEEN(SYSDATE@!,:B1)<=780 AND
                  MONTHS_BETWEEN(SYSDATE@!,:B2)>=253)
       9 - filter(MONTHS_BETWEEN(SYSDATE@!,:B1)>780)
    Statistics
              1  recursive calls
              0  db block gets
              0  consistent gets
              0  physical reads
              0  redo size
            538  bytes sent via SQL*Net to client
            396  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              4  sorts (memory)
              0  sorts (disk)
              3  rows processed
    SQL> ed

Maybe you are looking for