Running an update statement on two dependent attributes

Dear All,
I have a repair_job table that contains values for work_cost, parts_cost and total_cost which is the sum of the work and parts cost values. I want to run an update statement that doubles the work cost and, naturally, updates the value of total cost as well. I tried to run it as:
update repair_job
set work_cost = 2 * work_cost, total_cost = work_cost + parts_cost
where licence in (
select licence from car
where year = to_char(sysdate,'YYYY')
thinking that because the update of work_cost is first on the list, the updated value of total cost would be correct. It seems however that the update of total cost happens first and then the work cost is been updated; not sure what the reason is for that and it happens no matter what the order is in the update statement.
I know that I can do it in two separate statements, or use a trigger or PL/SQL to do it but I am curious as to why it has this behaviour. Also, is there a way to do it in a single SQL statement - i.e. forcing the update of the work_cost attribute first and then that of total_cost?
I look forward to hearing from you soon.
Regards,
George

Welcome to the forum!
>
thinking that because the update of work_cost is first on the list, the updated value of total cost would be correct. It seems however that the update of total cost happens first and then the work cost is been updated; not sure what the reason is for that and it happens no matter what the order is in the update statement.
I know that I can do it in two separate statements, or use a trigger or PL/SQL to do it but I am curious as to why it has this behaviour. Also, is there a way to do it in a single SQL statement - i.e. forcing the update of the work_cost attribute first and then that of total_cost?
>
The update to all columns of the row happen at the same time - there is no order involved.
You don't need two statements but you do need to do the updates based on the current value of the columns.
set work_cost = 2 * work_cost, total_cost = 2 * work_cost + parts_cost----------
In addition to sb92075's comments in 11 g you could also just define a virtual column for total_cost and then just query it like you do now.
total_cost   NUMBER GENERATED ALWAYS AS (work_cost + parts_cost) VIRTUAL,See this Oracle-base article for an example
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
Edited to supplement sb92075's reply by mentioning virtual columns

Similar Messages

  • Error while running batch update statement

    Hi
    We are experiencing the below error while running the batch update statement where in the IN clause have more than 80,000 entries. The IN clause is already handled for max 1000 values so it has multiple or clause
    like update...where id in (1,2...999) OR id in (1000,1001........) OR Id in ()...
    Error at Command Line:1 Column:0
    Error report:
    SQL Error: ORA-00603: ORACLE server session terminated by fatal error
    ORA-00600: internal error code, arguments: [kghfrh:ds], [0x2A9C5ABF50], [], [], [], [], [], []
    ORA-00600: internal error code, arguments: [kkoitbp-corruption], [], [], [], [], [], [], []
    00603. 00000 - "ORACLE server session terminated by fatal error"
    *Cause: An ORACLE server session is in an unrecoverable state.
    *Action: Login to ORACLE again so a new server session will be created
    Is there a limitation of oracle or some bug?
    Thanks

    http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/limits003.htm
    The limit on how long a SQL statement can be depends on many factors, including database configuration, disk space, and memoryI think you're over this limit.
    The only way is creating a temporary table with all the values and using
    IN (select ...)Max
    http://oracleitalia.wordpress.com

  • After running CC update I have TWO versions of Photoshop CC. Which should I delete?

    I had the CC version of Photoshop installed. A week or two ago I ran the CC updater and it listed something called "Adobe Photoshop CC 2014" in addition to "Adobe Photoshop CC." I selected "update all" and ended up with what appear to be two copies of Photoshop on my OS X Mac:
         Adobe Photoshop CC 2014 - version 15.0.0
         Adobe Photoshop CC - version 14.2.1
    Questions:
    It seems like the "CC 2014" copy is a new version and that I do not need the original "CC" installation, right?
    Should I just run the uninstaller in the "CC" version folder, and will this leave the "CC 2014" intact?
    Is there a reason this happened, and should I do anything to prevent a repeat?
    Thanks,
    Dan

    http://blogs.adobe.com/jkost/2014/06/installing-the-2014-release-of-creative-cloud.html
    This messages says (at least some) CC 2014 programs use NEW plugins https://forums.adobe.com/thread/1499663
    -so do not uninstall the older CC programs if you use plugins in your programs until you are sure you have plugins that work in CC2014
    If you are sure you don't need the old CC programs
    -http://helpx.adobe.com/creative-cloud/help/install-apps.html to install or uninstall
    -read reply #3 about the ORDER of uninstalling & installing https://forums.adobe.com/thread/1242671

  • Sudden increase in buffer gets per executions in update statement

    Hi,
    Recently we have encountered one performance issue, which is most likely caused by a sudden increase in the buffer gets per execution.
    The SQL is an update statement, updating a table using a primary key (we have checked to confirm the running execution plan is using the primary key), and one field being updated is a BLOB column.
    As shown in the below statistics, there is no major change in the number of executions during the every 20 minutes monitoring interval. However, the buffer gets per executions has been more than double, and the CPU time is almost doubled, hence the exec_time (elapsed time) has been doubled.
    The same SQL has been running for the past four years in multiple similar databases. The database is Oracle 9.2.0.4 running on Solaris 9. For the past 300 days, the average elapsed time per execution is about 0.0093s, while the average buffer gets per execution is about 670. The update statement has been executed about 9 times per second.
    The question is why there is a sudden increase in the buffer gets? The sudden increase happened twice for the past two days.
    <pre>
    B_TIME E_TIME EXECUTIONS_DIFF EXEC_TIME CPU_TIME BUFFER_GETS EXEC_PER_DAY
    2009-11-25-14:04 2009-11-25-14:23 8513 .0069 .0068 315.56 646329
    2009-11-25-14:23 2009-11-25-14:43 10170 .007 .0068 312.28 726188
    2009-11-25-14:43 2009-11-25-15:05 11873 .0072 .0069 320.17 787885
    2009-11-25-15:05 2009-11-25-15:23 8633 .011 .0101 844.83 675014
    2009-11-25-15:23 2009-11-25-15:44 9668 .0144 .0137 1448.51 680778
    2009-11-25-15:44 2009-11-25-16:04 9671 .0163 .0156 1809.04 702163
    2009-11-25-16:04 2009-11-25-16:25 10260 .0188 .0177 2107.67 711447
    2009-11-25-16:25 2009-11-25-16:44 9827 .0157 .0151 1834.3 739593
    2009-11-25-16:44 2009-11-25-17:05 10586 .0171 .0164 2008.25 714555
    2009-11-26-08:04 2009-11-26-08:24 11028 .0182 .0172 1979.61 800688
    2009-11-26-08:24 2009-11-26-08:44 10533 .0154 .0149 1734.62 750248
    2009-11-26-08:44 2009-11-26-09:04 9367 .018 .0168 2043.95 685274
    2009-11-26-09:04 2009-11-26-09:24 10307 .0214 .0201 2552.43 729938
    2009-11-26-09:24 2009-11-26-09:45 10932 .0251 .0234 3111.48 762328
    2009-11-26-09:45 2009-11-26-10:05 10992 .0278 .0254 3386.41 797404
    2009-11-26-15:03 2009-11-26-15:16 7183 .0425 .0348 4615.42 746824
    2009-11-26-15:16 2009-11-26-15:23 2921 .0417 .0373 4887.75 682092
    2009-11-26-15:23 2009-11-26-15:43 9597 .0393 .0352 4603.62 679656
    2009-11-26-15:43 2009-11-26-16:03 8797 .0411 .0362 4783.66 630755
    2009-11-26-16:03 2009-11-26-16:23 9957 .0453 .0391 5168.28 718100
    2009-11-26-16:23 2009-11-26-16:43 11209 .0436 .0369 4870.77 808395
    2009-11-26-16:43 2009-11-26-17:03 10729 .0428 .0375 5119.56 766103
    2009-11-26-17:03 2009-11-26-17:23 9116 .0409 .0363 4912.58 659098
    </pre>
    Yesterday I did a trace on one of the sessions running the update statement, and below is the tkprof output:
    <pre>
    call count cpu elapsed disk query current rows
    Parse 76 0.03 0.00 0 0 0 0
    Execute 76 4.58 5.14 0 567843 19034 76
    Fetch 0 0.00 0.00 0 0 0 0
    total 152 4.61 5.14 0 567843 19034 76
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    Parsing user id: 88
    Rows Row Source Operation
    1 UPDATE (cr=30 r=0 w=0 time=6232 us)
    1 INDEX UNIQUE SCAN <PK Index Name> (cr=3 r=0 w=0 time=58 us)(object id 81122)
    Elapsed times include waiting on following events:
    Event waited on Times Max. Wait Total Waited
    Waited--------------------------------------------------------------------------------
    SQL*Net message to client 152 0.00 0.00
    SQL*Net message from client 152 0.00 0.22
    SQL*Net more data from client 1894 0.00 0.03
    SQL*Net break/reset to client 152 0.00 0.00
    buffer busy waits 14 0.00 0.00
    enqueue 1 0.61 0.61
    </pre>
    GaoYuan

    Hi,
    I've reformatted your output for better understanding (with {noformat}...{noformat}):
    B_TIME           E_TIME           EXECUTIONS_DIFF  EXEC_TIME   CPU_TIME BUFFER_GETS EXEC_PER_DAY
    2009-11-25-14:04 2009-11-25-14:23            8513      .0069      .0068      315.56       646329
    2009-11-25-14:23 2009-11-25-14:43           10170       .007      .0068      312.28       726188
    2009-11-25-14:43 2009-11-25-15:05           11873      .0072      .0069      320.17       787885
    2009-11-25-15:05 2009-11-25-15:23            8633       .011      .0101      844.83       675014
    2009-11-25-15:23 2009-11-25-15:44            9668      .0144      .0137     1448.51       680778
    2009-11-25-15:44 2009-11-25-16:04            9671      .0163      .0156     1809.04       702163
    2009-11-25-16:04 2009-11-25-16:25           10260      .0188      .0177     2107.67       711447
    2009-11-25-16:25 2009-11-25-16:44            9827      .0157      .0151      1834.3       739593
    2009-11-25-16:44 2009-11-25-17:05           10586      .0171      .0164     2008.25       714555
    2009-11-26-08:04 2009-11-26-08:24           11028      .0182      .0172     1979.61       800688
    2009-11-26-08:24 2009-11-26-08:44           10533      .0154      .0149     1734.62       750248
    2009-11-26-08:44 2009-11-26-09:04            9367       .018      .0168     2043.95       685274
    2009-11-26-09:04 2009-11-26-09:24           10307      .0214      .0201     2552.43       729938
    2009-11-26-09:24 2009-11-26-09:45           10932      .0251      .0234     3111.48       762328
    2009-11-26-09:45 2009-11-26-10:05           10992      .0278      .0254     3386.41       797404
    2009-11-26-15:03 2009-11-26-15:16            7183      .0425      .0348     4615.42       746824
    2009-11-26-15:16 2009-11-26-15:23            2921      .0417      .0373     4887.75       682092
    2009-11-26-15:23 2009-11-26-15:43            9597      .0393      .0352     4603.62       679656
    2009-11-26-15:43 2009-11-26-16:03            8797      .0411      .0362     4783.66       630755
    2009-11-26-16:03 2009-11-26-16:23            9957      .0453      .0391     5168.28       718100
    2009-11-26-16:23 2009-11-26-16:43           11209      .0436      .0369     4870.77       808395
    2009-11-26-16:43 2009-11-26-17:03           10729      .0428      .0375     5119.56       766103
    2009-11-26-17:03 2009-11-26-17:23            9116      .0409      .0363     4912.58       659098
    call     count       cpu    elapsed       disk      query    current        rows
    Parse       76      0.03       0.00          0          0          0           0
    Execute     76      4.58       5.14          0     567843      19034          76
    Fetch        0      0.00       0.00          0          0          0           0
    total      152      4.61       5.14          0     567843      19034          76
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    Parsing user id: 88
    Rows     Row Source Operation
          1  UPDATE  (cr=30 r=0 w=0 time=6232 us)
          1   INDEX UNIQUE SCAN <PK Index Name(cr=3 r=0 w=0 time=58 us)(object id 81122)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      SQL*Net message to client                     152        0.00          0.00
      SQL*Net message from client                   152        0.00          0.22
      SQL*Net more data from client                1894        0.00          0.03
      SQL*Net break/reset to client                 152        0.00          0.00
      buffer busy waits                              14        0.00          0.00
      enqueue                                         1        0.61          0.61
    ********************************************************************************Can you please provide a DDL for the table, indexes, type of the tablespace(s) they reside in (ASSM/MSSM, extents sizes), the UPDATE statement, how many sessions on average/peaks are doing the same thing concurrently, how many sessions are working this table concurrently and how do they use it?

  • How to run Mass Update with faster speed?

    Hi,
    I am running an update statement of about 300K records and it is very slow. Any advice? Would it be faster if I replace the "in" with an "exists". Thanks.
    Update tablex
    set code ='a'
    WHERE
    id in (select id from tabley)
    and
    code = 'b'

    Would it be faster if I replace the "in" with an "exists".Could be, depending on your unknown database version, if you're on 10g and up, it probably won't matter.
    Here's an explanation:
    http://asktom.oracle.com/pls/asktom/f?p=100:11:7560115908991323::::P11_QUESTION_ID:953229842074

  • Update statement taking too long to execute

    Hi All,
    I'm trying to run this update statement. But its taking too long to execute.
        UPDATE ops_forecast_extract b SET position_id = (SELECT a.row_id
            FROM s_postn a
            WHERE UPPER(a.desc_text) = UPPER(TRIM(B.POSITION_NAME)))
            WHERE position_level = 7
            AND b.am_id IS NULL;
            SELECT COUNT(*) FROM S_POSTN;
            214665
            SELECT COUNT(*) FROM ops_forecast_extract;
            49366
    SELECT count(*)
            FROM s_postn a, ops_forecast_extract b
            WHERE UPPER(a.desc_text) = UPPER(TRIM(B.POSITION_NAME));
    575What could be the reason for update statement to execute so long?
    Thanks

    polasa wrote:
    Hi All,
    I'm trying to run this update statement. But its taking too long to execute.
    What could be the reason for update statement to execute so long?You haven't said what "too long" means, but a simple reason could be that the scalar subquery on "s_postn" is using a full table scan for each execution. Potentially this subquery gets executed for each row of the "ops_forecast_extract" table that satisfies your filter predicates. "Potentially" because of the cunning "filter/subquery optimization" of the Oracle runtime engine that attempts to cache the results of already executed instances of the subquery. Since the in-memory hash table that holds these cached results is of limited size, the optimization algorithm depends on the sort order of the data and could suffer from hash collisions it's unpredictable how well this optimization works in your particular case.
    You might want to check the execution plan, it should tell you at least how Oracle is going to execute the scalar subquery (it doesn't tell you anything about this "filter/subquery optimization" feature).
    Generic instructions how to generate a useful explain plan output and how to post it here follow:
    Could you please post an properly formatted explain plan output using DBMS_XPLAN.DISPLAY including the "Predicate Information" section below the plan to provide more details regarding your statement. Please use the {noformat}[{noformat}code{noformat}]{noformat} tag before and {noformat}[{noformat}/code{noformat}]{noformat} tag after or the {noformat}{{noformat}code{noformat}}{noformat} tag before and after to enhance readability of the output provided:
    In SQL*Plus:
    SET LINESIZE 130
    EXPLAIN PLAN FOR <your statement>;
    SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Note that the package DBMS_XPLAN.DISPLAY is only available from 9i on.
    In 9i and above, if the "Predicate Information" section is missing from the DBMS_XPLAN.DISPLAY output but you get instead the message "Plan table is old version" then you need to re-create your plan table using the server side script "$ORACLE_HOME/rdbms/admin/utlxplan.sql".
    In previous versions you could run the following in SQL*Plus (on the server) instead:
    @?/rdbms/admin/utlxplsA different approach in SQL*Plus:
    SET AUTOTRACE ON EXPLAIN
    <run your statement>;will also show the execution plan.
    In order to get a better understanding where your statement spends the time you might want to turn on SQL trace as described here:
    When your query takes too long ...
    and post the "tkprof" output here, too.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Unable to execute an update statement using CallableStatement

    Hi there,
    I'm trying to run an update statement from JUnit using java.sql.CallableStatement and oracle.jbo.server.DBTransaction.
            String updateSql =
                "update footable set barcol=TO_DATE('12-SEP-09','dd-MM-yy') where bazcol = 505";
            try {
                statement =
                        applnModule.getDBTransaction().createCallableStatement(updateSql,
                                                                               2);
                int executeUpdate = statement.executeUpdate();
                AppsLogger.write(this,
                                 "# records UPDATED ------------------>" + executeUpdate,
                                 AppsLogger.SEVERE);
            } catch (SQLException s) {
                s.printStackTrace();
                Assert.fail("Encountered SQL Exception: " + s);
            } finally {
                try {
                    if (statement != null)
                        statement.close();
                } catch (SQLException s) {
            }Below is the exception I get when I run the above code. There is no problem with the SQL - it works fine from SQLDeveloper.
    java.lang.AssertionError: Encountered SQL Exception: java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected
         org.junit.Assert.fail(Assert.java:91)
         sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         java.lang.reflect.Method.invoke(Method.java:597)
         org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
         org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
         org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
         org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
         org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
         org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.invokeTestMethod(AtfJUnit4JTestCaseClassRunner.java:362)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.runMethods(AtfJUnit4JTestCaseClassRunner.java:272)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner$1.run(AtfJUnit4JTestCaseClassRunner.java:265)
         org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
         org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
         oracle.apps.common.applicationsTestFramework.junit.internal.AtfJUnit4JTestCaseClassRunner.run(AtfJUnit4JTestCaseClassRunner.java:262)Edited by: 911023 on Oct 2, 2012 11:28 AM
    Edited by: 911023 on Oct 2, 2012 11:30 AM

    Using case statement.
    UPDATE gor_gold_post
       SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
                                   OR
                                   (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END,
           b49n      = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
                             OR
                             (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END
    WHERE tariff_code IN (169, 135, 136);Note: Code not tested.

  • Update statement getting ORA-00904 invalid identifier

    I am getting this ORA error when I try to conduct an update statement from a column value in one table to a like-named column in another table.
    For instance, in my select, shown below, this query runs like a champ, returning all of my records
    SELECT
    b.ID,
    b.ZIP, a.ZIP,
    a.NAME,
    a.LOCATION
    FROM TBL_ARCHIVE a
    INNER JOIN TBL_UAT b ON
    a.ID = b.ID
    WHERE
    b.ID > 470000  And b.ID <470100;However, if I try to run an update statement with any of the following, I get this error. It seems so strange to me that I'd get an error using the same columns in the update statement, but would return the desired results effectively from the select statement!
    one version of UPDATE
    UPDATE TBL_ARCHIVE a
    SET a.ZIP = TBL_UAT.ZIP
    WHERE TBL_UAT.ID = a.ID;and another
    UPDATE TBL_ARCHIVE
    SET a.ZIP  =
    (SELECT b.ZIP
    FROM TBL_UAT b
    WHERE b.ID <472500 And b.ID >471000)
    FROM TBL_ARCHIVE a
    WHERE a.ID = b.ID)
    WHERE ID IN
    (SELECT ID
    FROM TBL_UAT b
    WHERE b.ID  <472500 And b.ID >471000
    );^ - this one produces a SQL not properly ended. Error ORA-00933: SQL command not properly ended.
    I'm really unsure though, how what I thought was a fairly basic update statement wouldn't work. I'm using Oracle 11g but through either Toad or SQL Plus. I've gotten these same errors in both.
    Though MS Access runs slow as snails, I can manage to run the update statement successfully with it, a thousand records or so at a time. Problem is, I've got about 300K records needing updating.
    I've looked around for similar problems but haven't found one where someone wasn't either using a reserved word for a column, which I'm not, I don't believe, or a problem that really dealt with this error in the context of an update statement.
    But I'd welcome any enlightenment on this.

    rp0428 wrote:
    UPDATE TBL_ARCHIVE a
    SET a.ZIP = TBL_UAT.ZIP
    WHERE TBL_UAT.ID = a.ID;That isn't a valid query and neither is the other one.
    Please post the actual query you are using and the actual complete error message you are getting (everything about the error that is displayed).^^
    That is NOT a valid query?
    How else would you have an UPDATE statement created to set the value of a column in table A to the value of a (in this case, same named) column in table B?
    And keep them in order to update the records appropriately?
    I'll append the create statements momentarily.
    Thanks!
    CREATE TABLE TBL_UAT
    ( ID NUMBER(6),
    ZIP VARCHAR2(10 BYTE) ) and
    CREATE TABLE TBL_ARCHIVE
    ( ID NUMBER(6) NOT NULL, NAME VARCHAR2(50 BYTE),
    EMAIL VARCHAR2(50 BYTE),
    LOCATION VARCHAR2(50 BYTE),
    DEPARTMENT VARCHAR2(50 BYTE),
    PRIORITY VARCHAR2(50 BYTE),
    APPROVING_MGR_NAME VARCHAR2(50 BYTE),
    TYPE1 VARCHAR2(50 BYTE),
    TYPE2 VARCHAR2(50 BYTE),
    CONTACT_NAME VARCHAR2(50 BYTE),
    CONTACT_PHN_NO VARCHAR2(50 BYTE),
    LOAN_NUM VARCHAR2(50 BYTE),
    REF_ID VARCHAR2(50 BYTE),
    BORROWER_NAME VARCHAR2(50 BYTE),
    ADDRESS VARCHAR2(50 BYTE),
    CITY VARCHAR2(50 BYTE),
    ST VARCHAR2(50 BYTE),
    ZIP VARCHAR2(10 BYTE),
    SALE_DATE DATE,
    COMMENTS VARCHAR2(800 BYTE),
    TIME_REQ DATE,
    ACCTLOC VARCHAR2(50 BYTE),
    OTHER_ACCTLOC VARCHAR2(50 BYTE)) Hope this can be of assistance.
    Thanks, folks!
    Edited by: user515689 on Feb 7, 2012 11:59 AM

  • Update Statement Updating Too Many Rows

    Hiya,
    I am trying to run this update statement:
    UPDATE PROCEDURE_PRICE p
    SET p.term_date = (SELECT t.tdate
                        FROM PROCEDURE_PRICE_TMP t
                        WHERE p.seq_proc_price = t.zzz_nullterm_seq_proc_price
                        AND p.procedure_code = t.procedure_code
                        AND p.price_schedule = t.price_schedule)
    And it is updating all 600000+ records in the PROCEDURE_PRICE table.
    I am only expecting it to update 60 records, because that is what I find when running this query:
    select p.term_date,
         t.tdate,
         p.seq_proc_price,
         t.zzz_nullterm_seq_proc_price,
         p.procedure_code,
         t.procedure_code,
         p.price_schedule,
         t.price_schedule
    from procedure_price p, procedure_price_tmp t
    WHERE p.seq_proc_price = t.zzz_nullterm_seq_proc_price
    AND p.procedure_code = t.procedure_code
    AND p.price_schedule = t.price_schedule;
    Can't seem to figure out what is wrong, and I know it is something simple.
    Thanks in advance :).

    You probably want something like
    UPDATE PROCEDURE_PRICE p
       SET p.term_date = (SELECT t.tdate
                            FROM PROCEDURE_PRICE_TMP t
                           WHERE p.seq_proc_price = t.zzz_nullterm_seq_proc_price
                             AND p.procedure_code = t.procedure_code
                             AND p.price_schedule = t.price_schedule)
    WHERE EXISTS (SELECT 1
                     FROM PROCEDURE_PRICE_TMP t
                    WHERE p.seq_proc_price = t.zzz_nullterm_seq_proc_price
                      AND p.procedure_code = t.procedure_code
                      AND p.price_schedule = t.price_schedule)Basically, you want to slap a WHERE EXISTS clause on the UPDATE that ensures that your inner query returns a row.
    Justin

  • HELP! With parsing Update statement

    I am stuck and need help! The teacher has not gone over parsing with us and it is not on his scheduled topics list. But, I am a person that likes to scope out and learn new things. For our final project, we have to allow updates, delete and inserts into the 5 main tables of the Premiere Products database. I have done everything except for the updates. I can achieve the updates of the entities by pretty much hardcoding them and that is okay by the teacher, but I want to learn about parsing because Barbara from this site mentioned this to me.
    This is what I was able to write and I am getting errors:
    CREATE OR REPLACE PROCEDURE updatecust_proc (
    v_cust_num IN customera.cust_num%TYPE,
    v_attributetoupdate VARCHAR2 ,
    v_updatedvalue VARCHAR2 )
    AS
    e_invalidcustnum_error EXCEPTION;
    BEGIN
    v_isvalidcustnum := iscust(v_cust_num);
    IF (v_isvalidcustnum = FALSE) THEN
    RAISE e_invalidcustnum_error;
    END IF;
    PARSE(
    'UPDATE customer
    SET' &#0124; &#0124; v_attributetoupdate &#0124; &#0124; '=' &#0124; &#0124; v_updatedvalue &#0124; &#0124;
    'WHERE cust_num =' &#0124; &#0124; v_cust_num
    END;
    EXCEPTION
    WHEN e_invalidcustnum_error THEN
    DBMS_OUTPUT.PUT_LINE('Cannot be updated. Invalid customer number');
    END;
    Any help would be useful. I went to the Oracle help site but their examples are a little too complicated for me to understand, plus, I am not using any C code.
    Thanks in advance!
    Bob

    I will try putting in spaces to the areas that you mentioned to me. Thanks!
    I will try to explain the function just in case some other poeple don't understand what I am trying to do.
    This procedure is supposed to update the CUSTOMER entity. This entity has 7 attributes and I don't want to write out 7 UPDATE statements to changes a value. Instead, I want the name of the attribute to be passed to the proceudre so that the UPDATE statement can know which attribute to use. Barbara mentioned something about parsing and I attempted to try it out, but I am getting errors. Can someone help me with the procedure. BTW, function iscust() returns TRUE if the customer number is valid, otherwise, it returns false.
    Thanks,
    Bob

  • Update Statement With Date Field

    I'm trying to run an update statement and I want the date to be updated in the format:
    5/4/2010 12:31:54 PM
    If I run this query on dual it displays correctly: select to_char(sysdate,'DD/MM/YYYY HH12:MI:SS PM') from dual
    If I run this query though on my table I get a 'not a valid month' error.
    UPDATE WR_MEASURE_VALUE SET HOST_CORRECTED_VALUE=35,
    HOST_CORRECTED_DATE=to_char(sysdate,'DD/MM/YYYY HH12:MI:SS PM') WHERE WR_MEASURE_VALUE_OID= 474066
    what am I doing wrong and how can I get my update statement to update the date correctly in the 'DD/MM/YYYY HH12:MI:SS PM' form?
    Thanks
    Guess all I needed to say was HOST_CORRECTED_DATE= SYSDATE
    Thanks anyway
    Edited by: Rich75 on May 5, 2010 7:10 AM

    I want the date to be updated in the format: 5/4/2010 12:31:54 PMDate Formats are only of importance when you select/retrieve the dates.
    As you already understand, you can use TO_CHAR for that.
    If HOST_CORRECTED_DATE is of DATE datatype, then you can simply:
    update wr_measure_value
       set host_corrected_value = 35,
           host_corrected_date  = sysdate
    where wr_measure_value_oid = 474066;
    edit
    I see you already found out yourself ;)
    Edited by: hoek on May 5, 2010 4:15 PM

  • Errors while running BPEL and incorrect UPDATE statement

    Hi,
    I installed following software.
    1. Oracle Database 10g Release 2
    2. SOA Suite 10g Release 3
    3. Oracle JDeveloper (10.1.3.4)
    I developed a BPEL process to lock a userid in PeopleSoft.
    I have two issues.
    a) I am getting error as shown below
    b) its generating incorrect UPDATE statement, even though its assigning correct values in XML (UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?) i.e instead of setting OPRID in where clause its setting ACCTLOCK in where clause
    <messages><input><Invoke_1_update_InputVariable><part xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PsoprdefnCollection"><PsoprdefnCollection xmlns="http://xmlns.oracle.com/pcbpel/adapter/db/top/UpdateUserProfile">
    <Psoprdefn>
    <oprid>snagulapalli</oprid>
    <version/>
    <oprdefndesc/>
    <emplid/>
    <emailid/>
    <oprclass/>
    <rowsecclass/>
    <operpswd/>
    <encrypted/>
    <symbolicid/>
    <languageCd/>
    <multilang/>
    <currencyCd/>
    <lastpswdchange/>
    <acctlock>1</acctlock>
    <prcsprflcls/>
    <defaultnavhp/>
    <failedlogins/>
    <expent/>
    <oprtype/>
    <useridalias/>
    <lastsignondttm/>
    <lastupddttm/>
    <lastupdoprid>Laptop BPEL</lastupdoprid>
    <ptallowswitchuser/>
    </Psoprdefn>
    </PsoprdefnCollection>
    </part></Invoke_1_update_InputVariable></input><fault><remoteFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="code"><code>17002</code>
    </part><part name="summary"><summary>file:/D:/product/10.1.3.1/OracleAS_1/bpel/domains/default/tmp/.bpel_Sandbox_9.0_882edce22e996c64b48ea25cbe023033.tmp/Update_User_Profile.wsdl Update_User_Profile_ptt::update(PsoprdefnCollection) - WSIF JCA Execute of operation 'update' failed due to: DBWriteInteractionSpec Execute Failed Exception.
    update failed. Descriptor name: http://UpdateUserProfile.Psoprdefn. Caused by: Io exception: Connection reset by peer: socket write error
    ; nested exception is:
    ORABPEL-11616
    DBWriteInteractionSpec Execute Failed Exception.
    update failed. Descriptor name: http://UpdateUserProfile.Psoprdefn. Caused by: Io exception: Connection reset by peer: socket write error
    Caused by Exception TOPLINK-4002 (Oracle TopLink - 10g Release 3 (10.1.3.1.0) (Build 061004)): oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: Io exception: Connection reset by peer: socket write errorError Code: 17002
    Call:UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?)
    bind => Laptop BPEL, snagulapalli, 1
    Query:UpdateObjectQuery(<Psoprdefn 1 />).
    </summary>
    </part><part name="detail"><detail>
    Internal Exception: java.sql.SQLException: Io exception: Connection reset by peer: socket write errorError Code: 17002
    Call:UPDATE PSOPRDEFN SET LASTUPDOPRID = ?, OPRID = ? WHERE (ACCTLOCK = ?)
    bind => Laptop BPEL, snagulapalli, 1
    Query:UpdateObjectQuery(<Psoprdefn 1 />)</detail>
    </part></remoteFault></fault></messages>
    Regards,
    Shanti Nagulapalli.

    What version of SOA Suite are you using, SOA Suite 10g Release 3 is not enough information. Make sure that it is the same as your JDev version if it isn't then either downgrade the JDev or upgrade the SOA Suite.
    If you are still on SOA 10.1.3.1 then I would upgrade as there are many bugs in this release.
    These kind of strange errors are generally caused by incompatibility between design time (JDev) and run time (SOA Suite)
    cheers
    James

  • Update statement takes too long to run

    Hello,
    I am running this simple update statement, but it takes too long to run. It was running for 16 hours and then I cancelled it. It was not even finished. The destination table that I am updating has 2.6 million records, but I am only updating 206K records. If add ROWNUM <20 to the update statement works just fine and updates the right column with the right information. Do you have any ideas what could be wrong in my update statement? I am also using a DB link since CAP.ESS_LOOKUP table resides in different db from the destination table. We are running 11g Oracle Db.
    UPDATE DEV_OCS.DOCMETA IPM
    SET IPM.XIPM_APP_2_17 = (SELECT DISTINCT LKP.DOC_STATUS
    FROM [email protected] LKP
    WHERE LKP.DOC_NUM = IPM.XIPM_APP_2_1 AND
    IPM.XIPMSYS_APP_ID = 2
    WHERE
    IPM.XIPMSYS_APP_ID = 2;
    Thanks,
    Ilya

    matthew_morris wrote:
    In the first SQL, the SELECT against the remote table was a correlated subquery. the 'WHERE LKP.DOC_NUM = IPM.XIPM_APP_2_1 AND IPM.XIPMSYS_APP_ID = 2" means that the subquery had to run once for each row of DEV_OCS.DOCMETA being evaluated. This might have meant thousands of iterations, meaning a great deal of network traffic (not to mention each performing a DISTINCT operation). Queries where the data is split between two or more databases are much more expensive than queries using only tables in a single database.Sorry to disappoint you again, but with clause by itself doesn't prevent from "subquery had to run once for each row of DEV_OCS.DOCMETA being evaluated". For example:
    {code}
    SQL> set linesize 132
    SQL> explain plan for
    2 update emp e
    3 set deptno = (select t.deptno from dept@sol10 t where e.deptno = t.deptno)
    4 /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 3247731149
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Inst |IN-OUT|
    | 0 | UPDATE STATEMENT | | 14 | 42 | 17 (83)| 00:00:01 | | |
    | 1 | UPDATE | EMP | | | | | | |
    | 2 | TABLE ACCESS FULL| EMP | 14 | 42 | 3 (0)| 00:00:01 | | |
    | 3 | REMOTE | DEPT | 1 | 13 | 0 (0)| 00:00:01 | SOL10 | R->S |
    PLAN_TABLE_OUTPUT
    Remote SQL Information (identified by operation id):
    3 - SELECT "DEPTNO" FROM "DEPT" "T" WHERE "DEPTNO"=:1 (accessing 'SOL10' )
    16 rows selected.
    SQL> explain plan for
    2 update emp e
    3 set deptno = (with t as (select * from dept@sol10) select t.deptno from t where e.deptno = t.deptno)
    4 /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 3247731149
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Inst |IN-OUT|
    | 0 | UPDATE STATEMENT | | 14 | 42 | 17 (83)| 00:00:01 | | |
    | 1 | UPDATE | EMP | | | | | | |
    | 2 | TABLE ACCESS FULL| EMP | 14 | 42 | 3 (0)| 00:00:01 | | |
    | 3 | REMOTE | DEPT | 1 | 13 | 0 (0)| 00:00:01 | SOL10 | R->S |
    PLAN_TABLE_OUTPUT
    Remote SQL Information (identified by operation id):
    3 - SELECT "DEPTNO" FROM "DEPT" "DEPT" WHERE "DEPTNO"=:1 (accessing 'SOL10' )
    16 rows selected.
    SQL>
    {code}
    As you can see, WITH clause by itself guaranties nothing. We must force optimizer to materialize it:
    {code}
    SQL> explain plan for
    2 update emp e
    3 set deptno = (with t as (select /*+ materialize */ * from dept@sol10) select t.deptno from t where e.deptno = t.deptno
    4 /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 3568118945
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Inst |IN-OUT|
    | 0 | UPDATE STATEMENT | | 14 | 42 | 87 (17)| 00:00:02 | | |
    | 1 | UPDATE | EMP | | | | | | |
    | 2 | TABLE ACCESS FULL | EMP | 14 | 42 | 3 (0)| 00:00:01 | | |
    | 3 | TEMP TABLE TRANSFORMATION | | | | | | | |
    | 4 | LOAD AS SELECT | SYS_TEMP_0FD9D6603_1CEEEBC | | | | | | |
    | 5 | REMOTE | DEPT | 4 | 80 | 3 (0)| 00:00:01 | SOL10 | R->S |
    PLAN_TABLE_OUTPUT
    |* 6 | VIEW | | 4 | 52 | 2 (0)| 00:00:01 | | |
    | 7 | TABLE ACCESS FULL | SYS_TEMP_0FD9D6603_1CEEEBC | 4 | 80 | 2 (0)| 00:00:01 | | |
    Predicate Information (identified by operation id):
    6 - filter("T"."DEPTNO"=:B1)
    Remote SQL Information (identified by operation id):
    PLAN_TABLE_OUTPUT
    5 - SELECT "DEPTNO","DNAME","LOC" FROM "DEPT" "DEPT" (accessing 'SOL10' )
    25 rows selected.
    SQL>
    {code}
    I do know hint materialize is not documented, but I don't know any other way besides splitting statement in two to materialize it.
    SY.

  • Running SQL stored within a varchar2 for an update statement

    I have a table that stores option settings for different programs that run in our system. It just has an id (number), name (varchar2(4000)) and value (varchar2(4000)). I will have one record (id=1) that stores sql code to generate a date that is converted into a character format, something like "to_char(sysdate-60,'YYYY-MM-DD HH24:MI:SS')", and I have two records that store dates (id=2 and 3) as text.
    I want to run something like "update options set value=(select value from options where id=1) where id=2;", but I know that will store my sql code ('to_char(sysdate-60,''YYYY-MM-DD HH24:MI:SS'')'), and not a text-formatted date ('2009-04-16 13:04:05'). Is there any way within sql that I can use an update statement to store the results of value and not value itself? I generally use C++, so if I had to write a function to accomplish this, I would probably place it in the C++ program instead of a pl/sql function.

    "triggers...<shivers>
    Are you allowed to change database-side functionality?"
    For the most part, yes. We're a small group, and I still do most of the DBA work, despite being a C++ developer and having a part-time DBA. The few triggers we have created are for record id numbers on data that a customer will input through APEX, and I will have to keep those. They're only on inserts, do nothing if the id is populated, and don't exist on this table. The trigger here seems to be something deep within oracle that I cannot change.
    CREATE DATABASE LINK LOOPBACK USING '(description=(address=(protocol=beq)(program=/your/path/to/bin/oracle)))';
    UPDATE options SET VALUE = dbms_xmlgen.getxmltype('SELECT VALUE FROM options@loopback WHERE id = 1').EXTRACT('//text()').getstringval () WHERE id = 2;
    ERROR at line 1:
    ORA-12899: value too large for column "TEST"."OPTIONS"."VALUE" (actual: 65, maximum: 55)The "VALUE" column is a varchar(4000). I'm guessing something is too large for one of the oracle functions or there is a problem with a datatype, but I haven't found any answers. Will using extract affect my data in any way, say if my formula has a less than character for some strange reason? I happened to see a comparison between extract().getstringval() and extractval() at [http://pbarut.blogspot.com/2007/01/oracle-xmltype-exctractvalue-vs-extract.html], which makes it look like EXTRACT('//text()').getstringval () will change the less than to '&lt'. I can run tests to check once I get this working, but I'm not sure I can switch the procedure to extractval().
    Edited by: jbo5112 on Jun 15, 2009 5:25 PM -- The forum mangled my response when I actually typed the less than character

  • SQL Update Statement runs out of time

    Hi if I run the following SQL statement, never get the goal.
    The inventory table is about 20 000 000 records. Any Idea to tune that ?
    UPDATE inventory
    SET lotexp = (SELECT e.lotexp
    FROM st_itemexp e, inventory i
    WHERE i.itemnumber = e.itemnumber
    AND i.lotnumber = e.lotnumber)
    Thanks in advance Tom

    > Moreover, this query is extremely dangerous
    Exactly.. people tend to forget that if the correlated sub-query does not find a correlated row, it returns null - and that null value will update the existing value.
    Updating a 20 million row table is also.. well not dangerous.. but kind of foolish. The slowest operation on any RDBMS is I/O. Such a massive update means a massive amounts of the slowest possible operation. Which IMO is a bit foolish. Especially as an update is a lot more expensive resource wise than an insert in such a case. It could be a lot more sensible to perform the update instead as a CTAS (Create Table As Select).
    Also, one must question why such a large table is not partitioned. With partitioning one has a lot more flexibility. E.g. one may have 40 partitions each with a 500,000 rows. Which means that one can run partition updates in parallel and staggered, thus effectively managing the resource (undo/redo) footprint by dealing with multiple 500,000 row transactions and not a single 20 million transaction.

Maybe you are looking for