Decode function in Update statement

Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!

882300 wrote:
Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!If you really really really want to update the entire table, the syntax would be...
UPDATE book_trans
   SET
      pastdue_fees  = DECODE(SIGN((return_dte - due_dte)*2), -1, 0, 1, 12, Null);I took out all the single quotes. If you actually have a string column and you're storing entirely numbers in it then it should be declared as a NUMBER column and not a character (varchar2) column.
ALWAYS use the proper data type, it'll save you a ton of headaches in the future.
Also, since you're new to the forum, please read the FAQ so you learn the etiquette and what not.
http://wikis.sun.com/display/Forums/Forums+FAQ

Similar Messages

  • 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

  • How to use User defined Function in Update statement

    Hi All,
    I have written below update statement to update column based on value return by function. but it is not working. Could any one help me on this. This function will return only one value for each project.
    thanks in advance.
    UPDATE dg2.OD_PROJ_LOOKUP_TEMP o
    SET Months_In_Stage_Cnt = select Months_In_Stage_Cnt_ret(o.project_id) from dual;
    thanks
    deb

    hi,
    CREATE FUNCTION fn_emp_ename (p_empno IN emp.empno%TYPE)
       RETURN VARCHAR2
    IS
       v_ename   emp.ename%TYPE;
    BEGIN
       SELECT ename
         INTO v_ename
         FROM emp
        WHERE empno = p_empno;
       RETURN v_ename;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          RETURN NULL;
       WHEN OTHERS
       THEN
          RETURN NULL;
    END fn_emp_ename;
    SQL>
    SQL> select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7839 KING       PRESIDENT            17-NOV-81       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-81        950                    30
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
    14 rows selected.
    SQL>  select fn_emp_ename (empno) as  emp_name from emp;
    EMP_NAME
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    14 rows selected.
    SQL> update emp
      2  set ename= fn_emp_ename (7936)
      3  where empno=7934;
    1 row updated.
    SQL> commit;
    Commit complete.
    SQL>  select * from emp where empno=7934;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTN
          7934            CLERK           7782 23-JAN-82       1300                    1
    SQL> i hope this helps .........
    Thanks,
    P Prakash
    Edited by: prakash on Nov 17, 2011 11:52 PM

  • Update Statement through function

    Hi,
    I've got the following select statement that is pulling 29 records:
    select distinct aqh.quote_number, aqh.quote_header_id,aqh.quote_version, aql.line_number, msi.inventory_item_id, msi.segment1
    ,aqh.price_list_id, aqh.quote_expiration_date,aql.line_list_price, qpv.operand
    from aso_quote_headers_all aqh, aso_quote_lines_all aql,mtl_system_items msi
    ,qp_list_headers qlh, qp_list_lines qpl, qp_list_lines_v qpv
    where aqh.quote_header_id = aql.quote_header_id
    and aql.inventory_item_id = msi.inventory_item_id
    and aqh.price_list_id = qlh.list_header_id
    and qlh.list_header_id = qpl.list_header_id
    and qlh.list_header_id = qpv.list_header_id
    and qpl.list_line_id = qpv.list_line_id
    and msi.inventory_item_id = qpv.product_id
    and aqh.quote_number = :quote_number --56530
    i need to update the operand = list_line_price, for all the multiple 29 records. for every quote_number and quote_version_no.
    i need help in this to write a function with update statement.
    Thanks and Regards

    Hi,
    whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements) for all the tables, and the results you want from that data. In the case of a DML operation (like UPDATE) the results will be the contents of the changed table after the DML is finished.
    MERGE may be easier to use than UPDATE in this case.
    Put your existing query in the USING clause. The only columns it needs to include in the SELECT clause are those that identify which rows to update, and the new values (line_list_price in this case). I assume that the table to be updated has a unique key, which I called primary_key in the example below. This can actually be two or more columns, but it can't include the column being updated (operand).
    I assume that all the tables and all the conditions in your original query are necessary to get the columns in the SELECT clause. If not, you can simplify the query.
    MERGE INTO     qp_list_lines_v     dst
    USING     (
         select distinct aql.line_list_price, qpv.primary_key
         from aso_quote_headers_all aqh, aso_quote_lines_all aql,mtl_system_items msi
         ,qp_list_headers qlh, qp_list_lines qpl, qp_list_lines_v qpv
         where aqh.quote_header_id = aql.quote_header_id
         and aql.inventory_item_id = msi.inventory_item_id
         and aqh.price_list_id = qlh.list_header_id
         and qlh.list_header_id = qpl.list_header_id
         and qlh.list_header_id = qpv.list_header_id
         and qpl.list_line_id = qpv.list_line_id
         and msi.inventory_item_id = qpv.product_id
         and aqh.quote_number = :quote_number --56530
         )     src
    ON     (src.primary_key     = dst.primary_key)
    WHEN MATCHED THEN UPDATE
    SET     dst.operand     = src.list_line_price;You can use a MERGE statement like this in a PL/SQL procedure or function. (If you put this in a function, then you can only call the function from PL/SQL; you can't use a function that performs DML in a SQL query.)
    As posted above, the statement will use a single, given quote_number. (You mentioned another column, quote_version_number, that does not appear in your original query. It's unclear what you want with that column.)
    You can replace the bind variable :quote_number with an argument to the procedure, as Achyut suggested. It will still only work on a single, given quote_number.
    If you want it to work on all quote numbers at once, then omit the last condition (the one that references quote_number), or change it to
    AND   aqh.quote_number  IS NOT NULLdepending on your needs.
    If you want more help, post some sample data and the desired results.

  • Update statement with Aggregate function

    Hi All,
    I would like to update the records with sum of SAL+COMM+DEPTNO into SALCOMDEPT column for each row. Can we use SUM function in Update statement. Please help me out this
    See below:
    Table
    CREATE TABLE EMP
    EMPNO NUMBER(4) NOT NULL,
    ENAME VARCHAR2(10 CHAR),
    JOB VARCHAR2(9 CHAR),
    MGR NUMBER(4),
    HIREDATE DATE,
    SAL NUMBER(7,2),
    COMM NUMBER(7,2),
    DEPTNO NUMBER(2),
    SALCOMDEPT NUMBER
    Used update statement :
    UPDATE emp e1
    SET e1.salcomdept= (select sum(sumsal+comm+deptno) from emp e2 where e2.empno=e1.empno)
    WHERE e1.deptno = 10
    commit
    Thanks,
    User

    Adding these columns makes no sense, so I'll assume this is just an exercise.
    However, storing calculated columns like this is generally not a good idea. If one of the other columns is updated, your calculated column will be out of sync.
    One way around this is to create a simple view
    SQL> CREATE view EMP_v as
      2  select EMPNO
      3        ,ENAME
      4        ,JOB
      5        ,MGR
      6        ,HIREDATE
      7        ,SAL
      8        ,COMM
      9        ,DEPTNO
    10        ,(nvl(sal,0) + nvl(comm,0) + nvl(deptno,0)) SALCOMDEPT
    11  from   emp;
    View created.
    SQL> select sal, comm, deptno, salcomdept from emp_v;
                     SAL                 COMM               DEPTNO           SALCOMDEPT
                     800                                        20                  820
                    1600                  300                   30                 1930
                    1250                  500                   30                 1780
                    2975                                        20                 2995
                    1250                 1400                   30                 2680
                    2850                                        30                 2880
                    2450                                        10                 2460
                    3000                                        20                 3020
                    5000                                        10                 5010
                    1500                    0                   30                 1530
                    1100                                        20                 1120
                     950                                        30                  980
                    3000                                        20                 3020
                    1300                                        10                 1310
    14 rows selected.

  • Problem with decode function.

    Hi,
    Can anyone of you help me out in solving this?
    It is like i wish to give different select statements according to the value of a parameter entered by user USING DECODE FUNCTION.The select statement contains some other select statements inside it.So when i execute it,it is giving error like 'ORA-00913-too many values(even when i enclose select statements within brackets).

    ORA-00913 too many values
    Cause: The SQL statement requires two sets of values equal in number. This error occurs when the second set contains more items than the first set. For example, the subquery in a WHERE or HAVING clause may return too many columns, or a VALUES or SELECT clause may return more columns than are listed in the INSERT.
    Action: Check the number of items in each set and change the SQL statement to make them equal.
    the above is from oracle documentation. the brackets is not the problem, u must be using multiple items in the integrated decode queries. If the problem still exists post ur DML for further analysis.
    zaibi.

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Update Statement With Decode and Business Dates

    Hello everyone,
    I need to write a UPDATE statement using business date rule. In general, the due date is 30 days from the checkout date. If the due date falls on a Saturday or Sunday then the loan period is 32 days.
    I know that to test for a weekday, I'd need to use the to_char function in Oracle with the format of ‘D’. I did some research and found that to test which weekday November 12, 2007 falls on, I'd need to use the expression to_char(’12-NOV-2007’,’D’). This function returns a number between 1 and 7. 1 represents Sunday, 2 Monday, …,7 Saturday.
    What I really would need to do is write one UPDATE statement using an expression with the Decode function and the to_Char function:
    UPDATE book_trans SET due_dte = expression
    These are the transactions that will need to be updated:
    ISBN 0-07-225790-3 checked out on 15-NOV-2007 by employee 101(book_trans_id=1)
    ISBN 0-07-225790-3 checked out on 12-NOV-2007 by employee 151(book_trans_id=2)
    ISBN 0-201-69471-9 checked out on 14-NOV-2007 by employee 175(book_trans_id=3)
    ISBN 0-12-369379-9 checked out on 16-NOV-2007 by employee 201(book_trans_id=4)
    I manually calculated the due-dte and wrote update statement for each book_trans_id:
    UPDATE book_trans SET due_dte = '17-dec-07' WHERE book_trans_id = 1;
    UPDATE book_trans SET due_dte = '12-dec-07' WHERE book_trans_id = 2;
    UPDATE book_trans SET due_dte = '14-dec-07' WHERE book_trans_id = 3;
    UPDATE book_trans SET due_dte = '18-dec-07' WHERE book_trans_id = 4;
    As you can see, it's very cumbersome and I'd just like to know how to incorporate everything in one Update statement:
    UPDATE book_trans SET due_dte = expression
    so that if due date falls on Saturday or Sunday, the loan period is 32 days; weekday, loan period is 30 days.
    Any tips or help will be greatly appreciated. Thanks!

    Hi,
    882300 wrote:
    Hello everyone,
    I need to write a UPDATE statement using business date rule. In general, the due date is 30 days from the checkout date. If the due date falls on a Saturday or Sunday then the loan period is 32 days. That's equivalent to saying that the due date is normally 30 days after the checkout date, but if the checkout date falls on a Thursday or Friday, then the due date is 32 days after the checkout date. I used this equivalent in the statement below.
    I know that to test for a weekday, I'd need to use the to_char function in Oracle with the format of ‘D’. I did some research and found that to test which weekday November 12, 2007 falls on, I'd need to use the expression to_char(’12-NOV-2007’,’D’). This function returns a number between 1 and 7. 1 represents Sunday, 2 Monday, …,7 Saturday.That's just one way to find out the weekday, and it's error-prone because it depends on your NLS_TERRITORY setting. A more reliable way is to use 'DY' or 'DAY' as the 2nd argument to TO_CHAR. That depends on NLS_DATE_LANGUAGE, but you can explicitly set the language in the optional 3rd argument to TO_CHAR, which means your code will work the same no matter what the NLS settings happen to be. It's also easier to debug: you may have to think whether '1' means Sunday or Monday, but it's easy to remember that 'SUN' means Sunday.
    What I really would need to do is write one UPDATE statement using an expression with the Decode function and the to_Char function:
    UPDATE book_trans SET due_dte = expressionHere's one way:
    UPDATE  book_trans
    SET     due_dte = checkout_dte + CASE
                                      WHEN  TO_CHAR ( checkout_dte
                                             , 'fmDAY'
                                     , 'NLS_DATE_LANGUAGE=ENGLISH'
                                     ) IN ('THURSDAY', 'FRIDAY')
                             THEN  32
                             ELSE  30
                                  END
    WHERE   book_trans_id      IN (1, 2, 3, 4)
    ;This assumes that checkout date is a column in the same table.

  • Error while replacing IF statements with DECODE function in procedure

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

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

  • Operator in DECODE function in an INSERT statement

    Hello guys,
    consider I have some table EMP with only one column ID and want to insert new line like this:
    DECLARE
    x NUMBER := 1;
    BEGIN
    INSERT INTO EMP2 (ID) VALUES (DECODE((x mod 2),0,0,1));
    END;I got and old project, which was running on Oracle 8 and tried to compile it on Oracle 11g.
    When trying to run the above statement I always get ORA-00907 - missing right parentheses. To me it seems that it is not allowed to use an operator inside the decode function but I am pretty sure this was working on old Oracle 8.
    Does anybody know in which version this stoped to work?
    Thanks for help

    DECLARE
    x NUMBER := 1;
    BEGIN
    INSERT INTO EMP2 (ID) VALUES (DECODE(mod(x, 2),0,0,1));
    END;

  • Function call in update statement

    Hi,
    I have an update statement as follows
    update
    tableA
    set
    some_Ind = 0
    where
    cond1=val1
    and some_Ind = 1
    and f_test(param1, param2) ='Y'
    If i have say total 5 rows in tableA and the some_Ind is set to 1 for 2 rows.
    Will this update stmt, call the funtion for all 5 rows ? and then update only the rows matching the condition?
    Because i am expecting this update stmt to call the function for only the 2 rows which has the some_Ind as set but i get the message printed out 5 times for 5 rows but it updates only 2 rows.
    Since this function f_test is very complex, i need to call it for only those rows to be updated.
    Please give your suggestions....thanx...

    I just gave the test function to display the two parameters.
    This function is displaying the messages for all the 5 rows and not for the 2 rows which match the condition.
    CREATE OR REPLACE FUNCTION f_test1 (param1IN VARCHAR2,param2 IN VARCHAR2)
    RETURN VARCHAR2 IS
    retInd varchar2(1);
    begin
    dbms_output.put_line('param1: '||param1);
    dbms_output.put_line(param2: '||param2);
    retInd := 'Y';
    DBMS_OUTPUT.PUT_LINE('Val of retInd:'||retInd);
    RETURN retInd;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line('other exception ');
    RETURN 'N';
    END;

  • Explain plan on Update statement in function

    All,
    I have an update statement in a function and my explain plan shows:
    "Optimizer"     "Cost"     "Cardinality"     "Bytes"     
    "UPDATE STATEMENT"     "ALL_ROWS"     "2"     "1"     "7"     
    "UPDATE user.<table_name>"     ""     ""     ""     ""     
    "INDEX(UNIQUE SCAN) <table_name>.<PK_column_cons>"     "ANALYZED"     "1"     "1"     "7"
    Filtering is on index unique column, but cost is 1 what does that mean?
    do i need to change my update statement in function?
    Any ideas?
    Regards,
    ~ORA

    The cost is the optimizer's measure of how much effort it will take to execute the statement. For any statement the optimizer will evaluate a number of execution plans and choose the one with the lowest cost. I wouldn't worry too much about what it actually "means". However if you want to understand this subject in a lot more detail I would recommend the book Cost-Based Oracle Fundamentals by Jonathan Lewis.
    For your update statement the optimizer has chosen to access a single row by the primary key index, which is probably good enough, so you should not need to change it.
    The only faster way to access the data would be to use the row's ROWID directly. You would need to have fetched this explicitly in a previous SELECT statement, or you could use it implicitly with the WHERE CURRENT OF syntax for a cursor opened with FOR UPDATE.

  • Update statement that includes case, decode and from clause

    hello
    I've the following code. I ran this code in 9i and got the errror SQL command not properly ended. Can I use FROM clause in an update statement?
    CREATE OR REPLACE procedure NRI
    IS
    BEGIN
    UPDATE IEB2 SET SDI =
    (CASE PSDI WHEN '11' THEN '16'
    WHEN '13' THEN '38'
    WHEN '14' THEN '18'
    WHEN '23' THEN '21'
    WHEN '24' THEN '21'
    WHEN '31' THEN '27'
    WHEN '32' THEN '37'
    WHEN '33' THEN '38'
    WHEN '34' THEN '37'
    WHEN '43' THEN '46'
    WHEN '53' THEN '45'
    WHEN '55' THEN '48'
    WHEN '60' THEN '54'
    WHEN '61' THEN '57'
    WHEN '62' THEN '54'
    WHEN '63' THEN '56'
    WHEN '64' THEN '52'
    WHEN '70' THEN '21'
    WHEN '77' THEN '25'
    WHEN '78' THEN '41'
    WHEN '80' THEN '79'
    WHEN '85' THEN '75'
    WHEN '87' THEN '73'
    WHEN '15' THEN '15'
    WHEN '51' THEN '51'
    WHEN '88' THEN '88'
    WHEN '00' THEN '00'
    WHEN '99' THEN '99'
    WHEN '12' THEN DECODE(C.R_ID, 'N', '16','18')
    ELSE 'NONE' END)
    FROM D1.C C
    WHERE EXISTS
    (SELECT 1
    FROM D1.SD A, D2.SDP B, D1.C C
    WHERE A.SDN = B.DN
    AND B.SDI = '000000'
    AND B.PFI = 'W'
    AND B.CID = C.CID
    AND A.SDN = '0001500721');
    END;

    Your parenthesis look a tad messed up ... think this fixes them.
    CREATE OR REPLACE procedure NRI
    IS
    BEGIN
    UPDATE IEB2 SET SDI =
    SELECT
    CASE PSDI
      WHEN '11' THEN '16'
      WHEN '13' THEN '38'
      WHEN '14' THEN '18'
      WHEN '23' THEN '21'
      WHEN '24' THEN '21'
      WHEN '31' THEN '27'
      WHEN '32' THEN '37'
      WHEN '33' THEN '38'
      WHEN '34' THEN '37'
      WHEN '43' THEN '46'
      WHEN '53' THEN '45'
      WHEN '55' THEN '48'
      WHEN '60' THEN '54'
      WHEN '61' THEN '57'
      WHEN '62' THEN '54'
      WHEN '63' THEN '56'
      WHEN '64' THEN '52'
      WHEN '70' THEN '21'
      WHEN '77' THEN '25'
      WHEN '78' THEN '41'
      WHEN '80' THEN '79'
      WHEN '85' THEN '75'
      WHEN '87' THEN '73'
      WHEN '15' THEN '15'
      WHEN '51' THEN '51'
      WHEN '88' THEN '88'
      WHEN '00' THEN '00'
      WHEN '99' THEN '99'
      WHEN '12' THEN DECODE(C.R_ID, 'N', '16','18')
      ELSE 'NONE'
    END
    FROM D1.C C
    WHERE EXISTS 
        SELECT 1
        FROM D1.SD A, D2.SDP B, D1.C C
        WHERE A.SDN = B.DN
        AND B.SDI = '000000'
        AND B.PFI = 'W'
        AND B.CID = C.CID
        AND A.SDN = '0001500721'
    END;

  • Problem using DECODE() function with a Query of Queries

    I
    posted
    on my blog about an issue I was having trying to use the PL/SQL
    DECODE() function with a Coldfusion Query of Queries. This function
    works fine when you query a database for information. However, when
    you query another query, it seems that CF doesn't recognize it. I
    got errors stating that it found a left parenthesis where it
    expected a FROM key word. Here is a simplified version of what I am
    trying to do:
    quote:
    <!--- Simulated query; similar to what I was calling from
    my database --->
    <cfscript>
    qOriginal = queryNew("Name,Email,CountryCode",
    "VarChar,VarChar,VarChar");
    newRow = queryAddRow(qOriginal, 5);
    querySetCell(qOriginal, "Name", "Joe", 1);
    querySetCell(qOriginal, "Email", "[email protected]", 1);
    querySetCell(qOriginal, "CountryCode", "AMER", 1);
    querySetCell(qOriginal, "Name", "Sally", 2);
    querySetCell(qOriginal, "Email", "[email protected]", 2);
    querySetCell(qOriginal, "CountryCode", "AMER", 2);
    querySetCell(qOriginal, "Name", "Bob", 3);
    querySetCell(qOriginal, "Email", "[email protected]", 3);
    querySetCell(qOriginal, "CountryCode", "ASIA", 3);
    querySetCell(qOriginal, "Name", "Mary", 4);
    querySetCell(qOriginal, "Email", "[email protected]", 4);
    querySetCell(qOriginal, "CountryCode", "EURO", 4);
    querySetCell(qOriginal, "Name", "John", 5);
    querySetCell(qOriginal, "Email", "[email protected]", 5);
    querySetCell(qOriginal, "CountryCode", "EURO", 5);
    </cfscript>
    <cfquery name="qCountries" dbtype="query">
    SELECT DISTINCT(CountryCode) AS CountryCode,
    DECODE(states, "AMER", "North America &amp; Canada",
    "EURO", "Europe &amp; Africa", "ASIA", "Japan &amp;
    Asia","") CountryName
    FROM qOriginal
    ORDER BY CountryCode
    </cfquery>
    <cfdump var="#qCountries#">
    <!--- ========== END OF CODE ========== --->
    So running this returned the following error:
    Query Of Queries syntax error.
    Encountered "(. Incorrect Select Statement, Expecting a
    'FROM', but encountered '(' instead, A select statement should have
    a 'FROM' construct.
    Does anybody know why this doesn't work? Is it just not
    supported? Please note that I have also tried to use the CASE()
    function instead of DECODE() and that resulted in basically the
    same error. For now I an looping over my distinct query with a
    switch statement and manually loading a new query with the data how
    I want it. But it would be a lot cleaner and less code to have the
    DECODE() to work. Thx!

    DECODE() is an Oracle function, not generic SQL. Q-of-Q is a
    very limited subset of SQL and lacks many functions and clauses
    available in standard SQL, especially what you may be used to using
    in your particular RDBMS.
    See
    Query
    of Queries user guide
    Phil

  • Using DECODE Function to change data

    I am trying to use the Decode function in a SQL statement to find a field that has a specific type, and when it finds that type, I want to blank out the results in a different field.
    For example:
    DECODE(ADDR_TYPE,'HOME',PHONE='') HOME_PHONE

    something like:
    SQL> with t as
      2   (select 219 id,
      3           'BUS' addr_type,
      4           '505-555-5555' phone
      5      from dual
      6    union
      7    select 219 id,
      8           'HOME' addr_type,
      9           null   phone
    10      from dual
    11    union
    12    select 220 id,
    13           'BUS' addr_type,
    14           '101-111-1111'   phone
    15      from dual
    16    union
    17    select 220 id,
    18           'HOME' addr_type,
    19           null   phone
    20      from dual
    21    union
    22    select 223 id,
    23           'BUS' addr_type,
    24           '202-222-2222'   phone
    25      from dual
    26    union
    27    select 224 id,
    28           'HOME' addr_type,
    29           '303-333-3333'   phone
    30      from dual
    31    union
    32    select 225 id,
    33           'BUS' addr_type,
    34           null   phone
    35      from dual
    36    union
    37    select 226 id,
    38           'HOME' addr_type,
    39           null   phone
    40      from dual)
    41  select a.id,
    42         a.addr_type,
    43         decode(a.addr_type,'BUS',phone,null) phone
    44    from (select id, addr_type, phone,
    45                 row_number() over (partition by id order by id, decode(addr_type,'BUS',1,2)) rn
    46            from t) a
    47   where a.rn = 1;
            ID ADDR PHONE
           219 BUS  505-555-5555
           220 BUS  101-111-1111
           223 BUS  202-222-2222
           224 HOME
           225 BUS
           226 HOME
    6 rows selected.
    SQL>

Maybe you are looking for