SQL - update with joins

My database contains several tables in a parent-child relationship (5 levels). Tables for children contain unique (foreign key) of the parents. I need to update a field in the table below level with a hardcoded value (for example: the value d.field3 = 103), but only on the rows that match certain general criteria. Criteria are set at different levels of the hierarchy. I tried several approaches, but in the end, I still get the same error:

ORA-01779: cannot modify a column that is mapped to a table not preserved key

So far, I tried the following:
-create a view based on all joins (where b.fk = a.id etc.) and then write my update with the "filtering" query where clauses (for example: where b.field1 = 'abc' and c.field2 = 123... etc)
-create a query of update (without creating a preliminary view) which contains in the 'where' clause all joins and clauses of filtering

I am trying to adapt some scripts from SQL Server to Oracle, but nothing seems to work for this one. Your help is greatly appreciated.

Thank you
Alberto

Something like:

update CM_CRITERION_LINE_MASTER set function_id = 103
where criterion_master_id in (
  SELECT CM_CRITERION_MASTER.criterion_master_id
  from CM_CRITERION_MASTER, CM_STATEMENT, CM_CRITERION, CM_RULE, CM_CASE
  where CM_CRITERION_MASTER.criterion_master_id = CM_CRITERION.criterion_master_id
    and CM_CRITERION.statement_id = CM_STATEMENT.statement_id
    and CM_STATEMENT.rule_id = CM_RULE.rule_id
    and CM_RULE.case_id=CM_CASE.case_id
    and CM_CASE.case_category_id=2
    and CM_CASE.case_id > 799999
    and CM_RULE.rule_category_id 9
    and CM_RULE.task_id in (102,108,112,113,114,123,116)
)
  and CM_CRITERION_LINE_MASTER.function_id=11

Of course, you need to test.

Time to understand that SQL Server and Oracle, as well as other DBMS each differ :)

Gints Plivna
http://www.gplivna.EU

Tags: Database

Similar Questions

  • PL/SQL: Updated with a subquery, two tables * HELP *.

    I've really messed with instructions UPDATE in PL/SQL for awhile, so I'm a little frustrated now to try to get what seems to be a simple UPDATE to work. First of all, I have a SQL statement that produces what might be described as a key value of data matching.

    SELECT distinct i.id, i.code
    FROM the point i, pi product
    WHERE i.ccode = '12'
    AND i.scode = 'ACTIVE '.
    AND i.id IS NOT NULL
    AND pi.id = i.id
    AND IN i.id
    (SELECT DISTINCT ri.item_id
    CATEGORY ri
    WHERE ri.category_code = 'RRR')
    AND pi.new_id IS NULL;

    This produces a list of the ID of the ELEMENT and the corresponding CODES. What I'm trying to do is UPDATE the new_id PRODUCT with a combination of one field string "1212" concatenated with the ARTICLE of the SQL code above.

    So... If my listing above produces:

    IDENTIFICATION CODE
    012331 432412175321
    041234 421412421085
    065645 776545521108

    I need to update the PRODUCT table new_id where the PRODUCT.ID = '012331' to '121243241217532'

    Can anyone offer any help? This seems to be me stumping.

    Which can be also probably cut down to something like...

    update product
    set new_id = (SELECT '1212'||i.code
                  FROM item i
                  WHERE i.ccode = '12'
                  AND   i.scode = 'ACTIVE'
                  AND   i.id IN
                              (SELECT DISTINCT ri.item_id
                               FROM category ri
                               WHERE ri.category_code = 'RRR')
                  AND   i.id = product.id
                 )
    where new_id is null;
    
  • update with join

    If I want to the lock table 'AGREEMENT' and at the same time I need useful variables 'v_agreement_id, v_agr_version_id', then do it like the following below code:
      select a.ID,
          (select agrv.ID from AGR_VERSION agrv
          where agrv.LAST_VERSION = 'Y'
             and agrv.CLOSED_TIME is null
             and agrv.AGREEMENT_ID = a.ID
          )         
       into v_agreement_id, v_agr_version_id
       from AGREEMENT a   
       where a.ID = i_agreement_id
       for update;
    Or I can do so:
     select a.ID, agrv.ID      
          into v_agreement_id, v_agr_version_id
       from AGREEMENT a,
          AGR_VERSION agrv      
       where a.ID = i_agreement_id
          and agrv.LAST_VERSION = 'Y'
          and agrv.CLOSED_TIME is null
          and agrv.AGREEMENT_ID = a.ID
       for update;
    What is the difference between these 2 approuches? The fact the 'for update' understanding in the second approach it takes to lock?

    Well, beside the fact that two queries are not equal, the second request will lock two tables record result (LINE MODE EXCLUSIVE). While the first query will be locked only reviews in LINE MODE EXCLUSIVE tables. Here's the test scenario:

    SQL> create table test5 (a  number);
    
    Table created.
    
    SQL> ed
    Wrote file afiedt.buf
    
      1* create table test6 (b  number)
    SQL> /
    
    Table created.
    
    SQL> SELECT * FROM test5, test6
      2  for update;
    
    no rows selected
    
    SQL> ed
    Wrote file afiedt.buf
    
      1  SELECT NVL(lockwait,'ACTIVE')  AS Lockwait,
      2         DECODE(LOCKED_MODE, 2, 'ROW SHARE', 3, 'ROW EXCLUSIVE', 4, 'SHARE', 5,
      3              'SHARE ROW EXCLUSIVE', 6, 'EXCLUSIVE',  'UNKNOWN') AS Locked_mode
      4  FROM   SYS.V_$LOCKED_OBJECT A,
      5         SYS.ALL_OBJECTS B,
      6         SYS.V_$SESSION c
      7  WHERE  A.OBJECT_ID = B.OBJECT_ID
      8  AND    C.SID = A.SESSION_ID
      9* AND object_name like 'TEST%'
    SQL> /
    
    LOCKWAIT         LOCKED_MODE
    ---------------- -------------------
    ACTIVE           ROW EXCLUSIVE
    ACTIVE           ROW EXCLUSIVE
    
    SQL> rollback;
    
    Rollback complete.
    
    SQL> SELECT a , (SELECT b FROM test6 where test5.a=test6.b)
      2  FROM test5
      3  for update;
    
    no rows selected
    
    SQL> ed
    Wrote file afiedt.buf
    
      1  SELECT object_name, NVL(lockwait,'ACTIVE')  AS Lockwait,
      2         DECODE(LOCKED_MODE, 2, 'ROW SHARE', 3, 'ROW EXCLUSIVE', 4, 'SHARE', 5,
      3              'SHARE ROW EXCLUSIVE', 6, 'EXCLUSIVE',  'UNKNOWN') AS Locked_mode
      4  FROM   SYS.V_$LOCKED_OBJECT A,
      5         SYS.ALL_OBJECTS B,
      6         SYS.V_$SESSION c
      7  WHERE  A.OBJECT_ID = B.OBJECT_ID
      8  AND    C.SID = A.SESSION_ID
      9* AND object_name like 'TEST%'
    SQL> /
    
    OBJECT_NAME                    LOCKWAIT         LOCKED_MODE
    ------------------------------ ---------------- -------------------
    TEST5                          ACTIVE           ROW EXCLUSIVE
    

    If you want to lock a single table for the secodn query, use

    UPDATE OF

    Best regards

    Mohammed Riaz

  • update with joins? is there a simpler way?

    Hi all
    I have a table with 6 columns,
    col1: engine varchar2 (20).
    col2: number of measures.
    COL3: date,
    COL4: full time.
    col5: full minute.
    col6: flag of tank (1) (Y/N) default: Y

    the primary key defined on this table is a composite motor PK + date + time minute

    and another table B with 2 columns:
    col1: engine varchar2 (20).
    col2: maxrate number

    I need to turn the flag in the first table (col6) of Y to N on lines where (col2) as my first table meets certain conditions concerning the maxrate (col2 in my second table B); Let's say that whenever measures < 0.98 * maxrate.

    How do I do that?

    Thank you
    Kowalsky

    Hello

    Something like:

    UPDATE tableA TA
       SET TA.flag = CASE WHEN EXISTS (SELECT 1 FROM tableB TB WHERE TA.engine = TB.engine AND TA.measurement < 0.98 * TB.maxrate) THEN 'N' ELSE 'Y' END
     WHERE TA.flag = 'Y';
    

    In addition, a DATE column already hours, minutes and seconds, so no real don't need to get out separately (you will see them with TO_CHAR(date_col,'HH24:MI:SS').

  • Update query with join statement

    Hi guys, would check how to write a query to update with the inner join statement? The case is like this, I need to update PRD_ID on TBL A as below, based on the information of lookup table. The keys are based on the A03 column to the table time to condition only select records in LOOKUP_TBL where PRD_ID = 110001 then update to TBL_A for those who match the data and FIX_FLT = 1

    I have an update query and it works in SQL SERVER but not in ORACLE

    Update a PRD_ID = B.PRD_ID set

    Inner TBL_A A join B LOOKUP_TBL

    On A.A03 = B.A03

    AND A.FIX_FLT = 1 AND B.PRD_ID = '110001';

    TBL_A

    PRD_IDA03FIX_FLTTXNDATE
    1A11123/10/2010
    1A21110/24/2010
    1A33210/25/2010
    1A43210/26/2010
    1A53127/10/2010

    LOOKUP_TBL

    PRD_IDA03NOTE
    110001A1NULL VALUE
    110001A2NULL VALUE
    110005A3NULL VALUE
    110005A4NULL VALUE
    110001A5NULL VALUE

    You can write updates like this in Oracle.  It's called updatable join views.  Something like this:

    Update
    (select a.prd_id a_prd_id
    b.prd_id b_prd_id
    Inner TBL_A A join B LOOKUP_TBL
    On A.A03 = B.A03
    AND A.FIX_FLT = 1 AND B.PRD_ID = '110001'
    )
    Set a_prd_id = b_prd_id;

    But you must have the constraints appropriate in place, otherwise you will get the error "key preserved table.

  • Update with the join and group by

    Hi all

    I'm currently updating multiple columns in a table from an inner join query.
    First one recover the affected rows and values that I need for the update (which I call this subquery ED_Query).
    It is important to note that this subquery has a group of and and the having clause.

    My first attempt (using the query running in the SQL Server query) fails:

    SQL > update ED_Update
    2 set ED_Update.dtHoraInicioReal = ED_Query.dtHoraInicioReal,
    3 ED_Update.dtHoraFinReal = ED_Query.dtHoraFinReal,
    4 ED_Update.fPorcentajeRealizado = ED_Query.fPorcentajeRealizado
    HISTORICOS_AVANZA 5. HSAE_HIS_EXPEDICIONDIARIA ED_Update
    inner join 6)
    7. select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
    8 MAX (PT.iOrdenEnTrayecto) + 1 as iNumParadas,
    9 MAX (HPP.iOrden) as iOrdenUltimaParada,
    10 MIN (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60)) as dtHoraInicioReal,
    11 MAX (dtHora_LlegadaReal) as dtHoraFinReal,
    12 100 * cast ((MAX (HPP.iOrden) + 1) as float) / cast ((MAX (PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado
    13 of HISTORICOS_AVANZA. ED HSAE_HIS_EXPEDICIONDIARIA
    14 left join HISTORICOS_AVANZA. HSAE_HIS_HORAPASOPARADA HPP
    15 ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
    16 left join AVANZA. SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
    17 where ED.dtJornada = TO_DATE (January 14, 2013 ',' DD/MM/YYYY ') and ED.iIdExpedicion in (-131076)
    18 ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal group
    19 having ED.dtHoraInicioReal <>min (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60))
    20 or ED.dtHoraFinReal <>max (dtHora_LlegadaReal)
    (21) ED_Query
    22 we ED_Update.iIdExpedicionDiaria = ED_Query.iIdExpedicionDiaria;

    ERROR on line 5:
    ORA-00933: SQL not correctly completed command.

    Subquery (ED_Query) work fine in Oracle, so I suspect that the problems are when I mix with the update clause.

    SQL > select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,.
    2 MAX (PT.iOrdenEnTrayecto) + 1 as iNumParadas,
    3 MAX (HPP.iOrden) as iOrdenUltimaParada,
    4 MIN (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60)) as dtHoraInicioReal,
    5 MAX (dtHora_LlegadaReal) as dtHoraFinReal,
    6 100 * cast ((MAX (HPP.iOrden) + 1) as float) / cast ((MAX (PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
    7 ED.dtHoraInicioReal ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
    8 of HISTORICOS_AVANZA. ED HSAE_HIS_EXPEDICIONDIARIA
    9 left join HISTORICOS_AVANZA. HSAE_HIS_HORAPASOPARADA HPP
    10 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
    11 left join AVANZA. SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
    where the ED.dtJornada 12 = TO_DATE (January 14, 2013 ',' DD/MM/YYYY ') and ED.iIdExpedicion in (-131076)
    13 group of ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal, ED.fPorcentajeRealizado
    14 after ED.dtHoraInicioReal <>min (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60))
    15 or ED.dtHoraFinReal <>max (dtHora_LlegadaReal);

    IIDEXPEDICION IIDEXPEDICIONDIARIA INUMPARADAS IORDENULTIMAPARADA DTHORAINI
    ------------- ------------------- ----------- ------------------ ---------
    DTHORAFIN FPORCENTAJEREALIZADO ED_DTHORA ED_DTHORA ED_FPORCENTAJEREALIZADO
    --------- -------------------- --------- --------- -----------------------
    -131076 5662 406 15 JANUARY 13
    15 JANUARY 13 JANUARY 15, 13 15 JANUARY 13 0

    -131076 5663 406 15 JANUARY 13
    15 JANUARY 13 JANUARY 15, 13 15 JANUARY 13 0

    -131076 5664 406 15 JANUARY 13
    15 JANUARY 13 JANUARY 15, 13 15 JANUARY 13 0

    After reading this forum, I have change the query and try the following:

    SQL > UPDATE
    () 2
    3. select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
    4 MAX (PT.iOrdenEnTrayecto) + 1 as iNumParadas,
    5 MAX (HPP.iOrden) as iOrdenUltimaParada,
    6 MIN (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60)) as dtHoraInicioReal,
    7 MAX (dtHora_LlegadaReal) as dtHoraFinReal,
    8 100 * cast ((MAX (HPP.iOrden) + 1) as float) / cast ((MAX (PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
    9 ED.dtHoraInicioReal ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
    HISTORICOS_AVANZA 10. ED HSAE_HIS_EXPEDICIONDIARIA
    11 left join HISTORICOS_AVANZA. HSAE_HIS_HORAPASOPARADA HPP
    12 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
    13 left join AVANZA. SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
    14 where ED.dtJornada = TO_DATE (January 14, 2013 ',' DD/MM/YYYY ') and ED.iIdExpedicion in (-131076)
    Group 15 of ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal, ED.fPorcentajeRealizado
    16 having ED.dtHoraInicioReal <>min (dtHora_LlegadaReal + iTiempoEnParada /(24*60*60))
    17 or ED.dtHoraFinReal <>max (dtHora_LlegadaReal)
    18)
    19 SET ED_dtHoraInicioReal = dtHoraInicioReal,
    20 ED_dtHoraFinReal = dtHoraFinReal,
    21 ED_fPorcentajeRealizado = fPorcentajeRealizado;

    ERROR on line 2:
    ORA-01732: operation non-legal data manipulation on this point of view

    Little help?

    Thanl in advance.

    Published by: 984483 on 28-ene-2013 01:48

    Hello

    Thanks for posting the CREATE TABLE and INSERT.
    Don't forget to post the desired results of these sample data, i.e. the content of the or the tables changed after the UPDATE is made.

    Is that what you want ed_update to look like after that everyhting is finished?

    DATE01      NUMBERMAX  NUMBERSUM
    ---------- ---------- ----------
    01/01/2013         30         60
    02/01/2013          0          0
    03/01/2013          0          0
    

    If so, here's a way to do it:

    UPDATE     ed_update     u
    SET     (numbermax, numbersum) =
         (
                 SELECT  MAX (number01)
              ,     SUM (number01)
              FROM     ed_query
              WHERE     date01     = u.date01
         )
    WHERE     date01     = TO_DATE ('01/01/2013', 'DD/MM/YYYY')   -- If wanted
    ;
    

    In Oracle, INNER JOIN works only in the FROM clause of a SELECT statement.
    When you want to update a table with values from another table, you can do a subquery correlated (as I showed above) or use the MERGER instead of UPDATE.

  • Update with INNER JOIN

    Hello

    My update with the inner join does not seem to work.

    UPDATE RECAP R SET R.FLAVOR = (SELECT FN. FLAVOR_NDC FN FLAVOR, REPLACE CAP R WHERE R.NDC11 = FN. NDC11)

    When I write the query above, the inner circle question (SELECT FN. FLAVOR_NDC FN FLAVOR, REPLACE CAP R WHERE R.NDC11 = FN. NDC11) returns multiple lines, and it's a new syntax for me (as I was Teradata and SQL server).

    Can you please how this request can be written to make it work?

    I get the error message below

    SQL error: ORA-01427: einreihig subquery returns multiple rows
    01427 00000 - "einreihig subquery returns several lines.

    1. fix your code:

    UPDATE RECAP R SET R.FLAVOR = (SELECT FN.FLAVOR FROM FLAVOR_NDC FN WHERE R.NDC11 = FN.NDC11)
    

    2. you can use the fusion

    merge into RECAP R
    using FLAVOR_NDC FN
    on(R.NDC11 = FN.NDC11)
    when matched then
         update
         set R.FLAVOR = FN.FLAVOR
    

    Kind regards
    Malakshinov Sayan

  • Update statement with joins of tables and where Clause

    Hi, I have MS SQL background and I try to execute an update statement in Oracle with joins of tables. However, the syntax below does not work but I think it works for MS SQL.

    Basically, the base table must be attached to a master table trend with monthly snapshots, an account will be only an entry for a given date monthly. Where clause must be limited to accounts within a certain range of interest rates.

    The first approach returns command SQL ORA-00933 not correctly completed, and the second approach returns ORA-01427 row below query returns multiple rows. Can anyone help? Thanks in advance!



    1:

    Update PenaltyAll
    Set a.indicator = month (b.)
    of PenaltyAll an inner join Master b on a.acctno = b.accountnumber
    where a.monthend='01/31/2009' and b.date='12/31/2008' and b.apr < 20

    2:

    Update PenaltyAll
    adjustment indicator =
    (select to_char (b., 'MM')
    of PenaltyAll an inner join Master b on a.acctno = b.accountnumber
    "where to_char (a.monthend,'mm/dd/yyyy ') = 31 January 2009"
    (et to_char(b.date,'mm/dd/yyyy') = December 31, 2008 "
    and b.apr < 20)

    Published by: sqlrookie on August 21, 2009 07:04

    I edited my post, that was my mistake, ANC you try now?

  • Update with Outer Join, round 2

    Thanks for those of you who have helped me out on the first (I never thought that you could use a SELECTION of a line like that).

    However, here is a new version of my problem:

    I have three tables.
    Table_1 has a column that must be updated based on the Table_2 and Table_3 values.
    Table_1 both Table_2 have values used to determine which line of Table_3 to use.
    However, not all the rows in Table_1 has a corresponding line of Table_3, in which case the value of Table_3 to use is assumed to be 1.

    The tables and the corresponding columns are:

    TABLE_1
    value_1 - value update
    key_2 - a pointer to TABLE_2
    key_3a - a pointer to a TABLE_3 or a dummy value if there is no record of the TABLE_3

    TABLE_2
    key_2 - the primary key
    key_3b - a secondary pointer to TABLE_3
    Value_2 - a value to use in the calculation of TABLE_1.value_1

    TABLE_3
    key_3a - the first part of the unique key
    ley_3b - the second part of the unique key
    value_3 - a value to use in the calculation of TABLE_1.value_1

    If there is a line in table_3 which matches the values table_1.key_3a and table_2.key_3b (where table_2.key_2 = table_1.key_2):
    Set table_1.value_1 = table_2.value_2 * table_3.value_3
    If there is no such line in table_3:
    Set table_1.value_1 = table_2.value_2

    I want to do something like this:

    UPDATE table_1 t1
    SET = Value_1
    (
    SELECT T2.value_2 * NVL (t3.value_3, 1)
    IN table_2 t2
    LEFT JOIN t3 table_3
    WE (t3.key_3b = t2.key_3b and t3.key_3a = t1.key_3a)
    WHERE t2.key_2 = t1.key_2
    )

    However, Oracle does not t1 to be referenced in the outer join clause.
    (Assume that each value of key_2 in table_1 is table_2 as well: it is only the key_3 value that can be a model.)

    If I move "t3.key_3 = t1.key_3" to the WHERE clause, so t1.value_1 is null for lines without the corresponding value of the table_3.

    I can do it with a clone of table_1 using ROWID:

    UPDATE table_1 t1
    SET = Value_1
    (
    SELECT T2.value_2 * NVL (t3.value_3, 1)
    FROM table_1 t1a
    JOIN the t2 table_2
    ON t2.key_2 = t1a.key_2
    LEFT JOIN t3 table_3
    WE (t3.key_3b = t2.key_3b and t3.key_3a = t1a.key_3a)
    WHERE t1a.row_id = t1.row_id
    )

    However, is there an easier way to do it using ANSI joins (i.e. without (+) syntax)?
    I have this feeling I'm missing something obvious here.

    Sorry, I'm not sure understand your scenario this time. It is early and I did have my 64 ounces of caffiene still.

    I didn't look at the statement, you were trying to run and reformatting:

    SQL> UPDATE table_1 t1
      2  SET    value_1 = (SELECT t2.value_2 * NVL((select t3.value_3
      3                                             from   table_3 t3
      4                                             where  t3.key_3b = t2.key_3b
      5                                             and    t3.key_3a = t1.key_3a)
      6                                          ,1)
      7                    FROM   table_2 t2
      8                    WHERE  t2.key_2 = t1.key_2
      9                   )
     10  ;
    
    0 rows updated.
    

    I don't know if it will work for you, but at least it is syntactically correct.

  • Update with Outer Join

    Is it possible to do an update that involves an outer join on the updated table?

    Here's what I mean - now, I have something like:

    UPDATE table_1 t1
    SET col_1 =
    (
    SELECT t2.col_2
    IN table_2 t2
    WHERE t2.t1_key = t1.t1_key
    )
    WHERE THERE ARE
    (
    SELECT t2.*
    IN table_2 t2
    WHERE t2.t1_key = t1.t1_key
    );
    --
    UPDATE table_1 t1
    SET col_1 = 0
    WHERE THERE IS NO
    (
    SELECT t2.*
    IN table_2 t2
    WHERE t2.t1_key = t1.t1_key
    );

    Yes, I could set all values of table_1.col_1 = 0 first and then perform the update first, but it is inefficient because of the number of records in the table that could be updated twice.

    Is it possible to combine these two updates in a single update statement?

    You can simply use your first update and omit the WHERE EXISTS clause since you want to update all rows in table_1 anyway.

    If the subquery finds a match, it will update the selected value. Normally, a non-match would set the column to a null value, but you can solve this with NVL:

    SQL> select * from table_1;
    
                  T1_KEY                COL_1
    -------------------- --------------------
                       1                    1
                       2                    1
                       3                    1
                       4                    1
                       5                    1
                       6                    1
                       7                    1
                       8                    1
                       9                    1
    
    9 rows selected.
    
    SQL> select * from table_2;
    
                  T2_KEY                COL_2
    -------------------- --------------------
                       1                    9
                       3                    9
                       5                    9
    
    SQL> UPDATE table_1 t1
      2  SET    col_1 = nvl (
      3                       (SELECT t2.col_2
      4                        FROM   table_2 t2
      5                        WHERE  t2.t2_key = t1.t1_key
      6                       ),0
      7                     )
      8  ;
    
    9 rows updated.
    
    SQL> select * from table_1;
    
                  T1_KEY                COL_1
    -------------------- --------------------
                       1                    9
                       2                    0
                       3                    9
                       4                    0
                       5                    9
                       6                    0
                       7                    0
                       8                    0
                       9                    0
    
    9 rows selected.
    
  • Update statement with join other tables

    Hello
    I have two table is one that contains the xml file, basically, I need to read the xml file, then upgrade to another table based on certain conditions.
    UPDATE TRCB_XBRL_STG_2 STG 
    SET PROFIT = 
      case when xbrl.isconsolidatedacc='Y' and EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..."') is not null
      THEN EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..."')
      WHEN XBRL.ISCONSOLIDATEDACC='N' AND EXTRACTVALUE(XBRL.XBRLFILE,'//PROFIT ', 'xmlns:acra="..') IS NOT NULL
      THEN extractValue(XBRL.xbrlfile,'//PROFIT ', 'xmlns:acra=".."')
      ELSE STG.PROFIT
      END,
      SET REVENUE= 
      case when xbrl.isconsolidatedacc='Y' and EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE', 'xmlns:acra="..."') is not null
      THEN EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE.', 'xmlns:acra="..."')
      WHEN XBRL.ISCONSOLIDATEDACC='N' AND EXTRACTVALUE(XBRL.XBRLFILE,'//REVENUE', 'xmlns:acra="..') IS NOT NULL
      THEN extractValue(XBRL.xbrlfile,'//REVENUE', 'xmlns:acra="REVENUE"')
      ELSE STG.REVENUE
      END,
      ....
      ... (around 100 columns)
    FROM  TRCB_XBRL xbrl ,TRCB_XBRL_STG_2 STG 
    WHERE STG.XBRL_ID = XBRL.XBRL_ID 
    About 100 the number of columns, please someone suggest how to use the update with a join of two tables.

    Hello

    If all the values needed to update a given line from table_x come from the same line of table_y (or in the same row of a result set of a query on a number any of tables), then you can do something like this:

    UPDATE  table_x  x
    SET     (col1, col2, col3, ...)
    =     (
             SELECT  NVL (y.col1, x.col1)
             ,         NVL (y.col2, x.col2)
             ,         NVL (y.col3, x.col3)
             FROM    table_y  y
             WHERE   x.pkey   = y.expr
             AND         ...
         )
    WHERE   ...
    ;
    

    If the WHERE clause is based on the same line of table_y, then it will be probably easier and more efficient to use the MERGER instead of UPDATE.

    I hope that answers your question.
    If not, post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and the results desired from these data.
    In the case of a DML (UPDATE), for example, the sample data should show what looks like the tables before the DML, and the results will be the content of the or the tables changed after the DML.
    Explain, using specific examples, how you get these results from these data.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).
    See the FAQ forum {message identifier: = 9360002}

  • error in the update with a join query

    Hi all

    IM using oracle 10g on windows.

    im not able to use this update query with join...

    UPDATE
    b
    SET
    b.is_stud = 1
    Of
    b Boy
    JOIN IN-HOUSE
    the relationship r
    WE
    b.ID = r.boy_id;

    Thank you very much...
    MERGE into emp trg
    using(Select distinct b.ename ename,a.empno empno from emp a,
                 emp_status b where  a.empno=b.empno) src
    on
    (trg.empno=src.empno)
    when matched then
    update
    SET trg.name = src.ename;
    
  • Report of update SQL query with line selector. Update process.

    I have a report of update SQL query with the selectors in line.
    How to identify line selector in a process update on the page.

    I want to update some columns with a value of an area of selection on the page.

    With the help of the base:

    UPDATE table_name
    SET Column1 = value
    WHERE some_column = some_value

    I would need to do:

    UPDATE table_name
    SET column1 =: P1_select
    WHERE [line selector] =?

    Now sure how to identify [line selector] and/or validate it is checked.
    Thank you
    Bob

    Identify the name of the checkbox of the source of the page element, it should be of the fxx format (f01, f02... f50).
    Suppose that we f01.

    for i in 1 .. apex_application.g_f01.count
    loop
      UPDATE CONTRACTS
      SET SIP_LOAD_FLAG = :P16_STATUS
      where  =  apex_application.g_f01(i); --i'th checked record' primary key
    end loop;
    
  • Help with sql FULL OUTER JOIN

    Hi all
    I need assistance with SQL FULL OUTER JOIN.

    How to write with FULL OUTER JOIN, the query.
    I tried like


    I have 3 different queries.

    Query q: SELECT emp_id LN.emp_id.
    Sum (LN_amount) loan_amt
    MY_LON_TAB LN
    WHERE LN_amount > 20000
    LN.emp_id GROUP;



    Query b: SELECT PLN. EMP_ID emp_id,
    Sum (PLAN_AMOUNT) plan_amt
    FROM PLN MY_PLAN_TAB
    where PLAN_AMOUNT <>0
    GROUP BY PLN. EMP_ID;


    Query C:

    SELECT FLX. EMP_ID emp_id,
    SUM (PRORATE_AMOUNT) PRORATE_AMT
    OF MY_FLX_TAB FLX
    WHERE PRORATE_AMOUNT <>0
    FLX GROUP. EMP_ID;


    Suppose that the different subquery above 3 a, b, c respectively. each subquery with emp_id and respective amount.

    like a.emp_id, a.loan_amt
    b.emp_id, b.plan_amt
    c.emp_id, c.prorate_amt

    I show all the empid with their amount respective.
    schenario: If an account made, but not vice-versa b
    and B have record, but not vice versa c
    and a credit record but not vice versa c

    first: I have external is associated with the A and B
    Second: join external then complete the total outcome of (a & b) with c
    but empid c just as empty.


    My output is:

    emp_id a.loan_amt, b.plan_amt c.prorate_amt
    101 5000 null null
    102 4500 null 2000
    103 6700 null null


    How to solve the foregoing to the ANSI (FULL OUTER JOIN) method.
    Please suggest me.

    Thanks in advance...
    PKM

    Hello

    It is very difficult for anyone to say what you're doing wrong if they do not know what you are doing. Post your code FULL OUTER JOIN.
    My best guess is:

    WITH     a     AS
    (
         SELECT     ...      -- What you posted as query a
    )
    ,     b     AS
    (
         SELECT     ...      -- What you posted as query b
    )
    ,     c     AS
    (
         SELECT     ...      -- What you posted as query c
    )
    SELECT     COALESCE ( a.emp_id
               , b.emp_id
               , c.emp_id
               )     AS emp_id
    ,     ...     -- whatever other columns you want
    FROM          a
    FULL OUTER JOIN     b  ON     b.emp_id =            a.emp_id
    FULL OUTER JOIN     c  ON     c.emp_id = COALESCE (a.emp_id, b.emp_id)
    ;
    

    I hope that answers your question.
    If not, post a small example (CREATE TABLE and INSERT statements) data for all tables and the results expected from these data (if not what you have already posted).

  • sql Update query after matching with the string

    I am trying to reach the query that updates a table column with the value of the other table, after that he finds an exact match.

    So here's the table data and sample to create.
    create table code1 
    (
        codeid number,
        codedesc varchar2(60)
    );
    
    Insert into code1 values ( 1,'R1 CONTRACTS');
    
    Insert into code1 values ( 2,'R2 CONTRACTS');
    
    Insert into code1 values ( 3,'R3 CONTRACTS');
    
    Insert into code1 values ( 4,'R5 CONTRACTS');
    
    Insert into code1 values ( 5,'R9 CONTRACTS');
    
    Insert into code1 values ( 6,'R10 CONTRACTS');
    
    create table table1 
    (   
        tablekey number,
        prefix  varchar2(25),
        codedesc    varchar2(60)
    );
    
    Insert into table1(tablekey,prefix) values (1,'1001PAC');
    
    Insert into table1(tablekey,prefix) values (2,'1001MXT');
    
    Insert into table1(tablekey,prefix) values (3,'1002PAE');
    
    Insert into table1(tablekey,prefix) values (4,'1003PCS');
    
    Insert into table1(tablekey,prefix) values (5,'1004BDX');
    
    Insert into table1(tablekey,prefix) values (6,'1005PAC');
    
    Insert into table1(tablekey,prefix) values (7,'1006PAC');
    
    Insert into table1(tablekey,prefix) values (8,'1007LDR');
    
    Insert into table1(tablekey,prefix) values (9,'1009LCR');
    
    Insert into table1(tablekey,prefix) values (10,'1010LBR');
    
    Insert into table1(tablekey,prefix) values (11,'ABCDEF');
    I'm writing a query that would update the value of column - codedesc (currently Null) of the table1 table: after it is a string of column - table code1 codedesc.

    The logic for the match is, - take - 2nd column of table-codedesc code value and get 2 characters. For example, when the string is - R1 CONTRACTS, the string will be 1. (Select substr ("R1 CONTRACTS, 2, 2) of the double). -Output will be 1.

    Now,.
    Look in table 1 for the 3rd position of the prefix that corresponds to the string returned by the query above. So, if the prefix is '1001PAC', it should look for 2 value of figures from the 3rd position. So, in this case it will be 01. Digitally 01 and 1 are equal, then the match is found for this line in the table1 table, so we will need to update the value of the column codedesc with the "contracts of R1.
        tablekey,    prefix            codedesc    
    ---------- ------------------------------------------------------------
    
          1               1001PAC     R1 CONTRACTS    -- Needs to be update with this value. 
          2               1001MXT     R1 CONTRACTS
          3               1002PAE      R2 CONTRACTS
    ...
          11             ABCDEF                                --Null ( No Need to update when no match found).
    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    Appreciate your help.

    Hello

    You want to avoid TO_NUMBER, given that will cause an error if even a line has a number no (except space) in the wrong place.
    Use RTRIM to remove extra spaces at the end of the match_key and LPAD to add '0', if necessary, at the beginning:

    MERGE INTO     table1          dst
    USING   (
              SELECT  LPAD ( RTRIM ( SUBSTR ( codedesc
                                     , 2
                                   , 2
                                   )
                              )
                         , 2
                         , '0'
                         )          AS match_key
              ,     codedesc
              FROM     code1
         )               src
    ON     (src.match_key     = SUBSTR ( dst.prefix
                           , 3
                         , 2
                         )
         )
    WHEN MATCHED THEN UPDATE
         SET     dst.codedesc     = src.codedesc
    ;
    

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

Maybe you are looking for