Decode function in the Update statement

Hi all

I'm writing a query where I can update a pastdue_fees column in a table of book_trans based on a difference between the return_dte and due_dte columns.

I use Oracle SQL. That's what I have so far for my decoding function:

SQL > SELECT
2 DECODE (SIGN ((return_dte-due_dte) * 2),)
3 '-1 ', ' 0',
4 '1', '12', 'Null')
5 FROM book_trans;

DECO
----
Null value
12
Null value
0

If the logic is that, if the sign is - 1, the value in the return_dte column must be 0; If it is + 1, then it has 12 and everything else is Null.

So now, I have to conclude my function of decoding of the update statement to update the columns. However, I get the error messages.

The logic should be:
UPDATE book_trans SET PastDue_fees = decode (expression)

I gave him a few different tests 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 on line 2:
ORA-00936: lack of 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.
OF book_trans
*
ERROR on line 6:
ORA-00933: SQL not correctly completed command.

Any help or advice would be greatly appreciated I got SQL for about six weeks and not very competent!

Thank you!

882300 wrote:
Hi all

I'm writing a query where I can update a pastdue_fees column in a table of book_trans based on a difference between the return_dte and due_dte columns.

I use Oracle SQL. That's what I have so far for my decoding function:

SQL > SELECT
2 DECODE (SIGN ((return_dte-due_dte) * 2),)
3 '-1 ', ' 0',
4 '1', '12', 'Null')
5 FROM book_trans;

DECO
----
Null value
12
Null value
0

If the logic is that, if the sign is - 1, the value in the return_dte column must be 0; If it is + 1, then it has 12 and everything else is Null.

So now, I have to conclude my function of decoding of the update statement to update the columns. However, I get the error messages.

The logic should be:
UPDATE book_trans SET PastDue_fees = decode (expression)

I gave him a few different tests 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 on line 2:
ORA-00936: lack of 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.
OF book_trans
*
ERROR on line 6:
ORA-00933: SQL not correctly completed command.

Any help or advice would be greatly appreciated I got SQL for about six weeks and not very competent!

Thank you!

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 store all numbers in there so it must be reported as a NUMBER column and not a column of type character (varchar2).

ALWAYS use the appropriate data type, it will save you a ton of headaches in the future.

Also, since you are new to the forum, please read the FAQ to learn etiquette and what not.

http://wikis.Sun.com/display/Forums/Forums+FAQ

Tags: Database

Similar Questions

  • How to use the user defined function in the Update statement

    Hi all

    I wrote under the update statement to update the column based on the return value of function. but it does not work. Could someone help me on this. This function returns a single value for each project.

    Thanks in advance.

    UPDATE dg2. OD_PROJ_LOOKUP_TEMP o
    SET Months_In_Stage_Cnt = Months_In_Stage_Cnt_ret (o.project_id) select the double;


    Thank you
    Deb

    PLS-00231: function 'MONTHS_IN_STAGE_CNT_RET' cannot be used in SQL

    -What is the function that is declared private in a package? If Yes, then it must be public, otherwise the SQL engine cannot be used.

    Published by: Dom Brooks on November 18, 2011 09:43

  • Update using a function in the select statement

    Hello

    Is it possible to do the follwing.

    I tabele and a custom function, the custome service will update the column (amount) of the table based on the value of going through the function of the select statement.

    SELECT id, stock, where an id = get_update (id);

    Now


    Get_update function will return the same id I'm passing and update the column amount to a value in the
    table a.

    When I run the satament selection I have the updated data in the column amount in my first executtion, but if execute the same statement, again, I see the changes reflected. is it possible to get data updates to the first performance himself.

    the function is of type PRAGMA AUTONOMOUS_TRANSACTION

    Concerning

    Indeed a strange requirement and probably not the way to go in a production environment. But anyway is a way to achieve your goal

    SQL> create table a
    as
       select   12 id, 500 amount from dual
       union all
       select   13 id, 600 amount from dual
    /
    Table created.
    
    SQL> create or replace type a_typ as object (id number, amount number)
    /
    Type created.
    
    SQL> create or replace function get_id (pid number)
       return a_typ
    is
       pragma autonomous_transaction;
       l_a_typ   a_typ := a_typ (null, null);
    begin
          update   a
             set   amount = 800
           where   id = pid
       returning   id, amount      into   l_a_typ.id, l_a_typ.amount;
    
       commit;
    
       return l_a_typ;
    end get_id;
    /
    Function created.
    
    SQL> select   id, d.a_typ.amount amount
      from   a, (select get_id (13) a_typ from dual) d
     where   id = d.a_typ.id
    /
            ID     AMOUNT
    ---------- ----------
            13        800
    1 row selected.
    
  • the update statement modidy

    Hi all

    I have here is the update statement in my code

    UPDATE equip_stg stg

    SET stg.err = 'WRC '.

    WHERE DOES NOT EXIST (SELECT *)

    FROM (SELECT stg.*

    Of equip_stg stg.

    REASON_SETUP sea

    WHERE stg.equipment_fk = mer.equipment_pk

    AND stg.downtime_reason_code = mer.reason_code

    AND ((stg.status = 3 AND sea. REASON_TYPE = 1)

    OR (stg.status = 2 AND sea. REASON_TYPE = 3)

    OR (stg.status = 1 AND sea. REASON_TYPE = 4))

    ERS stg.downtime_reason_code AND IS NOT NULL)

    WHERE ers.equipment_fk = stg.equipment_fk

    AND ers.downtime_reason_code = stg.downtime_reason_code

    )

    AND stg.status IN (3,2,1)

    AND stg.downtime_reason_code IS NOT NULL;

    The statement above sets updated the column equip_stg in WRC if err for corresponding material and reason, there is no line in the REASON_SETUP table.

    I want to change the code above so that the validation above is first done with REASON_SETUP according to equipment and column of type of reason. Is there is no line for this type of material and the reason in this table, then he must hit lookup table.  Example, I have data from equipment EQP1, status = 3, then it should check if REASON_SETUP has everything save for EQP1 equipment and the reasoning of type 1. If she made the next record should be validated on the table otherwise come file should be validated against the lookup table. For the table of choice also I have same join conditions

    STG.equipment_fk = lookup.equipment_pk

    AND stg.downtime_reason_code = lookup.reason_code

    Thanks in advance.

    Kind regards

    Amrit

    Hello

    I think I see.  All lines for each (equipment, reason_type) will be removed completely on a table or another. reason_setup if possible and looking as if this combination never occurs in reason_type.  Another way to say it is that you want only (equipment, reason_type) groups of the best tablle, where reason_type is better than search.  Exactly what made a Request Top - N .  Here's a way to do it:

    UPDATE equip_stg

    SET err_code = "WRC".

    WHERE (equipment, downtime_reason_code) NOT IN

    (

    WITH union_data AS

    (

    SELECT 'A' preference AS, reason_code, reason_type, equipment

    OF reason_setup

    UNION ALL

    SELECT equipment, reason_type, reason_code, 'B' AS preferences

    SEARCH

    )

    got_r_num AS

    (

    SELECT equipment, reason_type, reason_code

    DENSE_RANK () (PARTITION BY MATERIAL, reason_type

    ORDER OF preference

    ) AS r_num

    Of union_data

    )

    SELECT equipment

    DECODE (reason_type

    1, 3

    3, 2

    )

    reason_code

    OF got_r_num

    WHERE r_num = 1

    )

    ;

    To see how this works, reconstruction of the NOT IN subquery, step by step.  First run just union_data as a stand-alone application.  When you understand what it does, run got_r_num and when you see what he's doing, run the set NOT IN subquery.

  • Commit to taking a lot of time for the update statement to bulk - 11 GR 2

    Hi team,

    We have a source table, which is the main table for our application.

    When I commit a transaction after update block, it takes long about 2 to 4 minutes.

    I don't understand why it takes too long...

    Could you please help me on this fix, please...

    It's the details on the table,

    Total number of records: 35 M record

    Validation interval: 500 records / commit

    Total scores: 3

    total number of columns: 95 - including primary, unique and foreign key columns (all columns will be updated for each update because update from the app online)

    Total no of the foreign key columns: 12

    Unique key column: 1

    Total index: 27 ( including the key index foreign 12 + 1 + 1 index of primary key Unique key index )

    example of update statement,

    UPDATE DIRECTORY_LISTING_STG
    SET
      COLUMN_1 = :VAL_1
      .
      .
      .
      COLUMN_94 = :VAL_94
    WHERE RECORD_KEY = :P_KEY_VAL;
    
    

    The table is.

    Plan hash value: 2997337465
    
    --------------------------------------------------------------------------------------------
    | Id  | Operation          | Name                  | Rows  | Bytes | Cost (%CPU)| Time     |
    --------------------------------------------------------------------------------------------
    |   0 | UPDATE STATEMENT   |                       |     1 |   308 |     3   (0)| 00:00:01 |
    |   1 |  UPDATE            | DIRECTORY_LISTING_STG |       |       |            |          |
    |*  2 |   INDEX UNIQUE SCAN| XPKDLS_STG_PARTPN     |     1 |   308 |     2   (0)| 00:00:01 |
    --------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       2 - access("RECORD_KEY"=TO_NUMBER(:P_KEY))
    
    

    Details of the database,

    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    "CORE 11.1.0.7.0 Production"
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    
    

    Thank you

    RAM

    2793617 wrote:

    Hello

    I am updating table via an application using Hibernate jdbc connection online.

    If the update statement will be sent to the database in a pack of 500 documents (batch update).

    Thanks Ram

    line-by-line UPDATE is slow by slow transformation

    In Oracle no other session can 'see' upgrade from uncommitted changes.

    The only way to significantly reduce the elapsed time is to have only 1 UPDATE & 1 COMMIT!

  • line blocking during the update statement


    Hello

    Using Oracle 11 g 2. If I call the following update statement of meeting A, meeting A locks the line until a statement commit / rollback is emanating from the session has. If the session B calls the same statement was updated and the same line, session B will have to wait until the lock is released in the session. However, application developers are expressed in terms of discussions. Would it be possible that the update statement is called in the same session by several requests? If so, the case statement can be evaluated without the line being locked which could lead to erroneous results? Trying to keep this short message.

    tableA has column (number of key, primary) and columnB (number)

    {

    Update tableA

    Define columnB = case when columnB = 3 then

    4

    When columnB = 4 then

    5

    on the other

    columnB

    end

    When columnA = 6;

    }

    2 applications (almost at the same time) in the same session could assess columnB 3. The goal would be the first query sets in column 4 and the second request sets in column 5.

    > However, application developers are expressed in terms of discussions.

    Of course, they are...

    But each application thread will have its own dedicated database session.

  • need help with the Update statement

    Hello
    I received a question in a course and I tried my best to respond, and now my brain is giving. I would really appreciate help with the update statement. I don't mind if you do not validate a solution, a little nudge in the right direction would be really useful. I'll post that I got.

    THE QUESTION
    / * For these agents disabled on more than seven missions, change their date of deactivation of the first date of deactivation of all the agents that have been activated in the same year as the agent that you update currently.
    */

    I have it divided into parts, here is my select statement to agents disabled on more than 7 missions, which produces the deactivation_dates in the agents table that I want to update...
    SELECT
    s.deactivation_date
    FROM
    (
    SELECT
    a.deactivation_date,
    count(m.mission_id) as nomissions
    FROM
    agents a
    INNER JOIN
    missions_agents m
    on
    a.agent_id=m.agent_id
    GROUP BY
    a.deactivation_date
    ) s
    WHERE
    s.nomissions>7 AND s.deactivation_date IS NOT NULL
    .. .and the code for the first date of deactivation for each year of activation agent
    select 
    a2.deactivation_date
    from
    agents a2
    where a2.deactivation_date= 
    (
    select min(a.deactivation_date)
    from 
    agents a
    where to_number(to_char(a.activation_date,'YYYY'))=to_number(to_char(a2.activation_date,'YYYY'))
    )
    ..... I am not real to marry these two statements together in the Update statement. I can't extract each date of deactivation produced in the first select statement and their match against the first date of deactivation in the year they have been activated for the second select statement.

    Any help greatly appreciated... :))

    I began to wonder how things would :)

    user8695469 wrote:
    First of all why he chooses the date the earliest of all agents

    UPDATE  AGENTS_COPY AC /* (1) */
    SET     DEACTIVATION_DATE = (
    SELECT  MIN(AGS.DEACTIVATION_DATE)
    FROM    AGENTS_COPY  AGS
    ,       AGENTS_COPY AC /* (2) */
    WHERE   TRUNC(AGS.ACTIVATION_DATE,'YEAR') = TRUNC(AC.ACTIVATION_DATE,'YEAR') /* (3) */
    )
    

    He recovers as soon as the subquery has not been correctly set in the SET clause. It seems you are trying to update a correlated, but we are still having a conceptual shift. I have added a few comments to your code above and below will explain.

    (1): when you do a correlated update it is useful to the table alias that you did right here.

    (2): this table statement is not necessary and is the reason why the FIRST deactivation date is selected. The alias that you use (3) refers to THIS table, not the one defined in the update statement. Remove the line indicated by (2) in the FROM clause and a correlated update will happen.

    and secondly why is it to update each row, when I thought that I'm just the lines where the agents are disabled and missions > 7? Pointers on where I'm wrong would be very appreciated. (SQL = stupid query language!) :)

    user8695469 wrote: then why is it to update each row, when I thought that I'm just the lines where the agents are disabled and missions > 7? Pointers on where I'm wrong would be very appreciated. (SQL = stupid query language!) :)

    
    WHERE EXISTS
    (
    SELECT
    a.agent_id,
    count(m.mission_id)
    FROM
    agents a
    /* INNER JOIN AC ON AC.AGENT_ID = A.AGENT_ID */
    INNER JOIN
    missions_agents m
    ON
    a.agent_id=m.agent_id
    GROUP BY
    a.agent_id,
    a.deactivation_date
    HAVING
    count(m.mission_id)>7 AND a.deactivation_date IS NOT NULL
    )
    

    Once again this problem is similar to the question above that a correlation update doesn't work. Test existence of lines in an EXISTS subquery. Since your subquery is not related to the table that you are trying to update, it will be always return a line and, therefore, it returns true for EACH LINE in the AGENTS table. To limit the game to only agents > 7 missions results, you need to add a join condition that references the table in your update statement. I added one above (with comments) as a sample.

    I recommend you look over all material that you have associated with correlated subqueries, including documents that I posted above. This seems to be what you're having the problem more with. If you need me to explain the concept of correlated queries any better please let me know.

    Thank you!

  • Helps when a special character and is included in the update statement

    Hi gurus,


    Please suggest me here. Your help is greatly appreciated.

    Am wririting an update statement on a column called Phone_num.description varchar2 (40).


    Here is my update statement:


    UPDATE Phone_num
    DESCRIPTION SET = "Beta - EMV / not for the purpose of Production."
    WHERE DIAL_NUMBER = 18662307528
    AND DESCRIPTION =' to & VERIZON';


    Here is the structure of the table:

    Phone_num. Description varchar2 (40)
    Phone_num. DIAL_NUMBER Number (11)

    Sample data:


    So when I run the sql script it pop-up is to highlight.

    Please suggest how I can handle this.

    Hello

    As John said, the easiest thing is just to disable the functionality of substitution of variables, saying:

    SET DEFINE OFF

    before the statement.  If you need to re - enable this feature, then tell

    ALL SET ON

    just after the statement.

    If you can't do that, then break the literal string in 2 parts immediately after the & character, like this:

    UPDATE Phone_num

    DESCRIPTION SET = "Beta - EMV / not for the purpose of Production."

    WHERE DIAL_NUMBER = 18662307528

    AND DESCRIPTION = ' to &'. | "VERIZON";

    You can't have a substitution variable whose name starts by ', then SQL ("more does not interpret &" as meaning a substituton variable.)

  • How to optimize the update statement so that the query is reading the same table?

    Hi all

    I have a process with the following UPDATE statement:

    Sales_val update

    SET ship_date =)
    Select max (hist.ship_date)

    FROM sales_hist hist

    WHERE hist. X_ID = A.X_ID

    AND hist. X_VAL = A.X_VAL)

    ) WHERE EXISTS (select * from sales_hist hist where )

    WHERE hist. X_ID = A.X_ID

    AND hist. X_VAL = A.X_VAL

    )

    sales_val - 50 lines mln (unique index)

    sales_hist - 20 mln ranks (unique index)

    I met many problems with waits and locks - how to optimize to avoid locks using the parameters of tables or changes of the declaration? or maybe is there another way to do optimization ?

    Kind regards

    Bolo

    Thank you for that. Collect in bulk Unfortunatelly + FORALL does not work with the types in 10g - solution is to use the FOR loop and is not as effective as FORALL in many cases. I do still some tests to solve this problem - I'll put you once it's done.

    EDIT: hash partitioning + fusion - 3-5 minutes (time), so for now it's the solution to the problem. Thank you all for the great discussion!

  • Handful of division by zero error in the update statement

    My dear welcom

    How and I overcame this problem in my update statement
    for exwmple, it comes to the table
    CREATE TABLE TEST4
    (
    A1 NUMBER,
    A2 NUMBER OF,
    A3 NUMBER
    )

    Insert into TEST4 a1, a2, values (15.3);
    Insert into TEST4 a1, a2, values (9.3);
    Insert into TEST4 a1, a2, values (12.0);

    commit;


    now, I'm trying to update the column a3 in Division a1/12

    Start
    update set of test4
    A3 = a1/a2;
    exception
    WHEN ZERO_DIVIDE THEN
    update set of test4
    A3 = 0;
    end;
    After you validate THE VALUE of A3 = 0;

    Can any onle help me


    I use oracle 10g R2
    Thanks in advance
    SQL> select  *
      2    from  test4
      3  /
    
            A1         A2         A3
    ---------- ---------- ----------
            15          3
             9          3
            12          0
    
    SQL> update  test4
      2     set  a3 = case a2 when 0 then 0 else a1 / a2 end
      3  /
    
    3 rows updated.
    
    SQL> select  *
      2    from  test4
      3  /
    
            A1         A2         A3
    ---------- ---------- ----------
            15          3          5
             9          3          3
            12          0          0
    
    SQL> 
    

    SY.

  • continue to shape function during the updating of the old masters and details without validation

    < font size = "2" > Hi all.

    Suppose we have the following tables
    Table 1: used
    Table 2: cities

    Employee has a foreign key (employee_city_id), see (city_id) in the Cities table.

    I do two forms - used and cities - for each table, in the form of the employee, I have run the query and modify some fields so that 'data block used' is CHANGED.
    In the second form I do the same thing - run query with the block in the status CHANGED, but when you try to commit the changes in the shape of cities a lock occurs on the table of cities and the form stop working until I have commit the changes in the shape of the employee.

    It is not make sense why lock happen?, it as two updated statements for each table.
    It should work as what follows, isn't it?
    -----
    1-
    update EMPLOYEE set ...
    will the table used in exclusive mode lock 'A LINE' and the table Cities in "UPDATE SHARE" if I change the column refer to the table of cities in the framework.
    2-
    update CITIES set ...
    Release the "update of SHARING" lock in cities if will exist and put in place "exclusive."
    -----

    So why the form stops working when you apply the above scenario up to approve changes in the form of the employee.
    Forms builder version: 6i & 10g
    Thank you.
    < / make >

    you have an index on employee_city_id?
    Long ago, I had a similar problem when updating from the main block: If there were no indexes on the secondary table, forms (oracle) locked (or tried to block) the table of any details.

  • How to use the escape character in the update statement.

    Hi all

    I'm trying to update using the following table update statement in sql, but whenever he asks me to enter the value 'and' below sql.
    UPDATE xyz_xyz
       SET NAME = 'ABC & PQR'
     WHERE ID = (SELECT ID
                   FROM abc_abc
                  WHERE NAME = 'C & PQR');
    Please let me know how to use escape character syntax or let me know if there is no alternative.

    Thank you
    Vishwas

    If you use SQL * more then use SET DEFINE OFF.

    Also, you can do something like this

    UPDATE xyz_xyz
       SET NAME = 'ABC' ||'&' || 'PQR'
     WHERE ID = (SELECT ID
                   FROM abc_abc
                  WHERE NAME = 'C' ||'&' ||'PQR');
    
  • What happens all by issuing the UPDATE statement

    Hi all

    Can you please tell me, what happens when problem user update statement in sga with background process?

    Thank you
    Sanjeev.

    Hope you've finished reading your old post. "what happens all by issuing the select statement.
    What happens all by issuing the select statement

    Open the document since the last post and search "how Oracle database of the LMD processes."

  • Solution probably really Simple (where in the Update statement)

    Right,

    I have a table. In this table, there are 5 fields for the sake of arguments:

    COLUMN_ONE COLUMN_THREE COLUMN_FOUR COLUMN_FIVE COLUMN_TWO

    On this table there will be duplicate records, but only the column 1, column 2 and 3 on these "duplicate" files will be the same, column 4 will be different (column 4 is not a unique identifier, but if there are duplicate records, it will be different at least 2 records). Column 5 is not yet filled, all null.

    I need a way to update column 5 of these duplicate records. However, let me update on one of the folders and the criteria for this will be where column_4 = "Hello".

    So far I came with an update statement similar to the following, but I don't know where with her:

    UPDATE DANS_TABLE
    SET COLUMN_five = "DUPLICATE".
    WHERE EXISTS (SELECT column_one | column_two | column_three, COUNT (*))
    OF DANS_TABLE
    GROUP BY column_one | column_two | column_three
    SEEN (COUNT (*) > 1)) and column_four = 'Hello ';

    For any help, thank you very much! Much appreciated,

    Dan

    This is the query that updates that one line duplicated to column_five. I hope this helps...

    UPDATE DANS_TABLE x 1
    SET COLUMN_five = "DUPLICATE".
    WHERE THERE ARE
    (
    Select r_id of
    (select max (rowid) r_id, column_one | column_two | column_three)
    of DANS_TABLE t1 where exists
    (
    Select str of
    (
    SELECT column_one | column_two | column_three str, COUNT (*)
    OF DANS_TABLE
    GROUP BY column_one | column_two | column_three
    SEEN (COUNT (*) > 1)
    ) t2 where t2.str = t1.column_one | T1.column_two | T1.column_three
    ) column_one group | column_two | column_three
    ) x 2 where x 1 .rowid = 2 .r_id x
    ) and column_four = 'Hello ';

  • Question about the update statement

    Hi all


    UPDATE table_name
    SET Column1 = value, column2 = value2
    WHERE condition;

    I have an update like this statement. What happens when I run the above statement, when there is no column named Column2 in the table? If it creates a column named column2 and value2 using?

    Instead should first create a new column named Column2 in the table first and then run this update statement?

    Please, someone good to explain.

    Hi, this statement (it is a dml statement) will give an error, because the Column2 does not exist in the table. You must add the Column2 by an alter (ddl statement) statement. Then, you can try to execute your statement.

    Kind regards
    Saby

    Published by: 793420 on September 7, 2010 14:48

    Published by: 793420 on September 7, 2010 14:48

Maybe you are looking for