Update statement with joining other tables

Hi ,
I have two table one is containing xml file , basically i need to read from those xml file then update to another table based on some condition.
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 Number of columns are around 100 , please anyone suggest how to use update statement with joining two tables.

Hi,
If all the values needed to update a given row of table_x are coming from the same row of table_y (or from the same row of a result set of a query involving any number 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 depends on the same row of table_y, then it will probably be simpler and more efficient to use MERGE instead of UPDATE.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ {message:id=9360002}

Similar Messages

  • Update statement with joins

    Hi all, consider the tables and data below
    CREATE TABLE table1 (id NUMBER, a NUMBER, b NUMBER) ;
    CREATE TABLE table2 (id NUMBER, c NUMBER, d NUMBER);
    INSERT INTO table1 VALUES(111,2,0);
    INSERT INTO table1 VALUES(111,1,2);
    INSERT INTO table1 VALUES(111,1,3);
    INSERT INTO table1 VALUES(222,1,3);
    INSERT INTO table2 VALUES(111,5,8);
    INSERT INTO table2 VALUES(222,6,7);
    what i want to do is write a UPDATE STATEMENT that joins the two tables BY id
    and update table1 rows. i want to include the following CASE statement
    UPDATE COLUMN a intable1 according to this logic
    case
    WHEN b >0
    THEN nvl(c,b)
    ELSE
    d
    END
    so table1 after the update should look like this
    id    a   b
    111   8   0
    111   5   2
    111   5   3
    222   6   3can somebody help write a update statement that update table1 according to case statement and joins both tables to get the values necessary? thanks

    Hooray for sample tables!
    SQL> alter table table2 add constraint table2_pk primary key (id);
    Table altered.
    SQL> update
      2     (select t1.a
      3            ,case when t1.b > 0 then nvl(t2.c, t1.b)
      4                  else t2.d
      5             end new_value
      6      from   table1 t1
      7      join   table2 t2
      8             on t1.id = t2.id
      9     )
    10  set a = new_value;
    4 rows updated.
    SQL> select * from table1;
                      ID                    A                    B
                     111                    8                    0
                     111                    5                    2
                     111                    5                    3
                     222                    6                    3

  • Need help to write a query for Update statement with  join

    Hi there,
    The following update statement gives me error as the given table in set statement is invalid. But its the right table .
    Is the statement correct? Please help .
    update (
           select distinct(vpproadside.VEHICLE_CRED_OVERRIDE.vin)            
             from vpproadside.VEHICLE_CRED_OVERRIDE
             join vpproadside.vpp_vehicle
               on vpproadside.vpp_vehicle.vin = vpproadside.VEHICLE_CRED_OVERRIDE.vin
            where VPP_CARRIER_SEQ_NUMBER = 90
              and EXPIRY_DATE = '17-MAR-10'
       set vpproadside.VEHICLE_CRED_OVERRIDE.EXPIRY_DATE = '15-SEP-10';Edited by: Indhu Ram on Mar 12, 2010 1:00 PM
    Edited by: Indhu Ram on Mar 12, 2010 1:22 PM
    Edited by: Indhu Ram on Mar 12, 2010 2:35 PM
    Edited by: Indhu Ram on Mar 15, 2010 8:04 AM
    Edited by: Indhu Ram on Mar 15, 2010 8:06 AM
    Edited by: Indhu Ram on Mar 15, 2010 8:28 AM

    Ask Tom has very good discussion about this, if UPDATE does not work for PK issue, you can use MERGE
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:760068400346785797

  • Update statement with inner join

    Hello everyone. I am am trying to do an update statement with an inner join. I have found several examples of SQL statements that work with Sql server and mysql but they don't work in Oracle. Does anyone know the proper way in Oracle 10G? I am trying to update all fields in one table from fields in another table.
    for example:
    UPDATE table3
    SET
    TL3.name = TL2.name,
    TL3.status = TL2.status,
    TL3.date = TL2.date
    FROM table3 TL3 JOIN table2 TL2
    ON (TL3.unique_id = TL2.unique_id);
    any help will be appreciated.

    Hi,
    You can also use MERGE, like this:
    MERGE INTO  table3     dst
    USING   (
             SELECT  unique_id
             ,         name
             ,         status
             ,         dt          -- DATE is not a good column name
             FROM    table2
         )          src
    ON     (dst.unique_id     = src.unique_id)
    WHEN MATCHED THEN UPDATE
    SET     dst.name     = src.name
    ,     dst.status     = src.status
    ,     dst.dt          = src.dt
    ;Unlike UPDATE, this lets you avoid essentially doing the same sub-query twice: once in the SET clause and then again in the WHERE clause.
    Like UPDATE, you don't acutally join the table being changed (table3 in this case) to the other table(s); that is, the FROM clause of the suib-query does not include table3.
    Riedelme is right; you'll get better response to SQL questions like this in the SQL and PL/SQL forum:
    PL/SQL

  • Is it possible that my update stats used only correct tables?

    Whenever there is a schedule maintenance run I receive a error:
    Executing the query "UPDATE STATISTICS [Perf].[PerfHourly_F65954CD35A54..." failed with the following error: "Table 'PerfHourly_F65954CD35A549E886A48E53F148F277' does not exist.". Possible failure reasons: Problems with the query, "ResultSet"
    property not set correctly, parameters not set correctly, or connection not established correctly.
    Is it possible that my update stats used only correct  tables?
    Thanks

    Use below script ...(change if required)
    USE [dbname]
    go
    DECLARE @mytable_id INT
    DECLARE @mytable VARCHAR(100)
    DECLARE @owner VARCHAR(128)
    DECLARE @SQL VARCHAR(256)
    SELECT @mytable_id = MIN(object_id)
    FROM sys.tables WITH(NOLOCK)
    WHERE is_ms_shipped = 0
    WHILE @mytable_id IS NOT NULL
    BEGIN
     SELECT @owner = SCHEMA_NAME(schema_id), @mytable = name
     FROM sys.tables
     WHERE object_id = @mytable_id
     SELECT @SQL = 'UPDATE STATISTICS '+ QUOTENAME(@owner) +'.' + QUOTENAME(@mytable) +' WITH ALL, FULLSCAN;'
     Print @SQL
     EXEC (@SQL)
     SELECT @mytable_id = MIN(object_id)
     FROM sys.tables WITH(NOLOCK)
     WHERE object_id > @mytable_id
      AND is_ms_shipped = 0
    END
    Or use below for required table only but it will not execute only generate script, make change as per ur requirements:
    SELECT X.*,
      ISNULL(CASE
        WHEN X.[Total Rows]<=1000
        THEN
          CASE
            WHEN [Percent Modified] >=20.0
            THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name] + ' WITH ALL, FULLSCAN  --20% Small Table Rule'
          END
        WHEN [Percent Modified] = 100.00
        THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  --100% No real Stats Rule'
        --WHEN X.[Rows Modified] > 1000
        --THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  --1000 Rows Modified Rule'
        ELSE
          CASE
            WHEN X.[Total Rows] > 1000000000 --billion rows
            THEN CASE
                   WHEN [Percent Modified] > 0.1
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 1B Big Table Rule'
                 END
            WHEN X.[Total Rows] > 100000000  --hundred million rows
            THEN CASE
                   WHEN [Percent Modified] > 1.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 100M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 10000000   --ten million rows
            THEN CASE
                   WHEN [Percent Modified] > 2.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 10M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 1000000    --million rows
            THEN CASE
                   WHEN [Percent Modified] > 5.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 1M Big Table Rule'
                 END
            WHEN X.[Total Rows] > 100000     --hundred thousand rows
            THEN CASE
                   WHEN [Percent Modified] > 10.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 100K Big Table Rule'
                 END
            WHEN X.[Total Rows] > 10000      --ten thousand rows
            THEN CASE
                   WHEN [Percent Modified] > 20.0
                   THEN 'UPDATE STATISTICS ' + [Schema Name] + '.' + [Table Name]     + ' WITH ALL, FULLSCAN  -- 10K Big Table Rule'
                 END
            END
      END,'') AS [Statistics SQL]
    FROM (
    SELECT  DISTINCT
            DB_NAME()   AS [Database],
            S.name      AS [Schema Name],
            T.name      AS [Table Name],
            I.rowmodctr AS [Rows Modified],
            P.rows      AS [Total Rows],
            CASE
              WHEN I.rowmodctr > P.rows
              THEN 100
              ELSE CONVERT(decimal(8,2),((I.rowmodctr * 1.0) / P.rows * 1.) * 100.0)
            END AS [Percent Modified]
    FROM
            sys.partitions P
            INNER JOIN sys.tables  T ON P.object_Id = T.object_id
            INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
            INNER JOIN sysindexes  I ON P.object_id = I.id
    WHERE P.index_id in (0,1)
      AND I.rowmodctr > 0
    ) X
    WHERE [Rows Modified] > 1000
    ORDER BY [Rows Modified] DESC
    Please click "Propose As Answer"
    if a post solves your problem, or "Vote As Helpful" if a post has been useful
    to you

  • UPDATE Statement executing for whole table even when WHERE Clause is presen

    Hi Friends,
    I have a problem in a stored procedure where i have written an update statement with a where clause. At a time only one row should get updated depending upon unique identifier in where clause.
    But whats happening is that Update statement is getting executed for all the rows in the table neglecting the WHERE clause. I am not getting the clue as to why this is happening. Here is the stored Procedure And the update statement is in BOLD :-
    CREATE OR REPLACE PROCEDURE MDMADM.proc_MDM_InsertCntryDetails
    CntryMasterCode IN VARCHAR2,
    CntryName IN VARCHAR2,
    MDMUser IN VARCHAR2,
    Exist IN INTEGER,
    status IN VARCHAR2,
    Inserted_By IN VARCHAR2 DEFAULT NULL,
    Modified_By IN VARCHAR2 DEFAULT NULL,
    Mdm_Code IN NUMBER DEFAULT 0,
    Action IN VARCHAR2 DEFAULT 'add',
    XGenAttNames IN VARCHAR2 DEFAULT NULL,
    XGenAttValues IN VARCHAR2 DEFAULT NULL,
    MirusAttNames IN VARCHAR2 DEFAULT NULL,
    MirusAttValues IN VARCHAR2 DEFAULT NULL,
    GenisysAttNames IN VARCHAR2 DEFAULT NULL,
    GenisysAttValues IN VARCHAR2 DEFAULT NULL,
    XGenModify IN VARCHAR2 DEFAULT NULL,
    MirusModify IN VARCHAR2 DEFAULT NULL,
    GenisysModify IN VARCHAR2 DEFAULT NULL
    IS
    strSQLXGen VARCHAR(1000);
    strSQLMirus VARCHAR(1000);
    strSQLGenisys VARCHAR(1000);
    nMaxMDMCode INTEGER;
    ifExist INTEGER;
    NAME: proc_MDM_InsertCntryDetails
    PURPOSE:
    REVISIONS:
    Ver Date Author Description
    1.0 7/3/2009 1. Created this procedure.
    NOTES:
    Automatically available Auto Replace Keywords:
    Object Name: proc_MDM_InsertCntryDetails
    Sysdate: 7/3/2009
    Date and Time: 7/3/2009, 7:11:20 PM, and 7/3/2009 7:11:20 PM
    Username: (set in TOAD Options, Procedure Editor)
    Table Name: (set in the "New PL/SQL Object" dialog)
    BEGIN
    SELECT COUNT(*) INTO ifExist FROM MDM_COUNTRY_MASTER;
    IF ifExist = 0 THEN
    SELECT 1 INTO nMaxMDMCode FROM DUAL;
    ELSE
    SELECT MAX(MDM_CODE)+1 INTO nMaxMDMCode FROM MDM_COUNTRY_MASTER;
    END IF;
    IF Action='add' THEN
    INSERT INTO MDM_COUNTRY_MASTER(MDM_CODE,MDM_MASTER_CODE,MDM_DESCRIPTION,MDM_USER,MDM_EXIST,MDM_STATUS,MDM_ACTION,DAT_INSERT_DATE,DAT_INSERTED_BY)
         VALUES(nMaxMDMCode,CntryMasterCode,CntryName,MDMUser,Exist,status,Action,SYSDATE,Inserted_By);
    strSQLXGen := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || XGenAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || nMaxMDMCode || ',' || '''' || 'XGen' || '''' || ',1,' || XGenAttValues || ',' || '''' || Inserted_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLXGen;
    strSQLMirus := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || MirusAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || nMaxMDMCode || ',' || '''' || 'Mirus' || '''' || ',2,' || MirusAttValues || ',' || '''' || Inserted_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLMirus;
    strSQLGenisys := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || GenisysAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || nMaxMDMCode || ',' || '''' || 'Genisys' || '''' || ',3,' || GenisysAttValues || ',' || '''' || Inserted_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLGenisys;
    ELSE
    UPDATE MDM_COUNTRY_MASTER
    SET MDM_DESCRIPTION=CntryName,DAT_MODIFIED_BY=Modified_By,DAT_MODIFY_DATE=SYSDATE,
    MDM_USER=MDMUser,MDM_ACTION=Action,MDM_STATUS=status,MDM_EXIST=Exist WHERE MDM_CODE=Mdm_Code;
    SELECT COUNT(*) INTO ifExist FROM MDM_COUNTRY_MAPPING WHERE SYSTEM_CODE=1 AND MDM_CODE=Mdm_Code ;
    IF ifExist = 0 THEN
    strSQLXGen := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || XGenAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || Mdm_Code || ',' || '''' || 'XGen' || '''' || ',1,' || XGenAttValues || ',' || '''' || Modified_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLXGen ;
    ELSE
    strSQLXGen := 'UPDATE MDM_COUNTRY_MAPPING SET ' || XGenModify || ',DAT_MODIFY_DATE=SYSDATE,DAT_MODIFIED_BY=' || '''' || Modified_By || '''' || ' WHERE MDM_CODE=' || Mdm_Code || ' and SYSTEM_CODE=1' ;
    EXECUTE IMMEDIATE strSQLXGen ;
    END IF;
    SELECT COUNT(*) INTO ifExist FROM MDM_COUNTRY_MAPPING WHERE SYSTEM_CODE=2 AND MDM_CODE=Mdm_Code ;
    IF ifExist = 0 THEN
    strSQLMirus := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || MirusAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || Mdm_Code || ',' || '''' || 'Mirus' || '''' || ',2,' || MirusAttValues || ',' || '''' || Modified_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLMirus ;
    ELSE
    strSQLMirus := 'UPDATE MDM_COUNTRY_MAPPING SET ' || MirusModify || ',DAT_MODIFY_DATE=SYSDATE,DAT_MODIFIED_BY=' || '''' || Modified_By || '''' || ' WHERE MDM_CODE=' || Mdm_Code || ' and SYSTEM_CODE=2' ;
    EXECUTE IMMEDIATE strSQLMirus ;
    END IF;
    SELECT COUNT(*) INTO ifExist FROM MDM_COUNTRY_MAPPING WHERE SYSTEM_CODE=3 AND MDM_CODE=Mdm_Code;
    IF ifExist = 0 THEN
    strSQLGenisys := 'INSERT INTO MDM_COUNTRY_MAPPING(MDM_CODE,SYSTEM_NAME,SYSTEM_CODE,' || GenisysAttNames || ',DAT_INSERTED_BY,DAT_INSERT_DATE) ' ||
    'VALUES(' || Mdm_Code || ',' || '''' || 'Genisys' || '''' || ',3,' || GenisysAttValues || ',' || '''' || Modified_By || '''' || ',SYSDATE)';
    EXECUTE IMMEDIATE strSQLGenisys ;
    ELSE
    strSQLGenisys := 'UPDATE MDM_COUNTRY_MAPPING SET ' || GenisysModify || ',DAT_MODIFY_DATE=SYSDATE,DAT_MODIFIED_BY=' || '''' || Modified_By || '''' || ' WHERE MDM_CODE=' || Mdm_Code || ' and SYSTEM_CODE=3' ;
    EXECUTE IMMEDIATE strSQLGenisys ;
    END IF;
    END IF;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    NULL;
    WHEN OTHERS THEN
    -- Consider logging the error and then re-raise
    RAISE;
    END proc_MDM_InsertCntryDetails;
    Thanks

    It might be helpful to search this forum and google for PL/SQL (variables, stored procs, etc) naming standards. There are quite a few out there and you can choose one that works for you.
    As an example, a lot of standards adopt naming prefixes, ie v_ for VARCHAR variable, n_ for NUMBER variable, pv_ for paramater VARCHAR, etc.

  • Update statement with inner join issues

    I have searched for the answer on this and not really 100%....so figured I would ask...be nice :)
    what have I done wrong? Or am I just going about this the wrong way? I have looked at the oracle docs and I can't find an example showing me this. I do see where you SET values based on the select query results. I want to update the result of a query based on the join with static values....
    UPDATE table.a
    SET table.a_STATUS=9,table.a.INDEX = 'N'
    WHERE (SELECT table.a INNER JOIN table.b ON (table.a.COMPANY = table.b.COMPANY) AND (table.a.PO_NUMBER =table.b.PO_NUMBER) AND (table.a.PO_RELEASE =table.b.PO_RELEASE) AND (table.a.PO_CODE =table.b.PO_CODE) AND (table.a_STATUS=1) AND (table.b.CLOSED_FL = 'Y'));

    Hi,
    Welcome to the forum!
    user11360811 wrote:
    I have searched for the answer on this and not really 100%....so figured I would ask...be nice :)
    what have I done wrong? Or am I just going about this the wrong way? I have looked at the oracle docs and I can't find an example showing me this. I do see where you SET values based on the select query results. I want to update the result of a query based on the join with static values....
    UPDATE table.aThat's updating a table called A in a schema called TABLE (which is not a good name for any user-named object). Are those really your table and schema names? Perhaps you meant to have an underscore instead of a dot:
    UPDATE  table_ais much, much more reasonable. It means the table name is TABLE_A (a perfectly good name) in the current schema.
    SET table.a_STATUS=9,table.a.INDEX = 'N'
    WHERE ( ...There's a syntax error. You can't just say
    "WHERE (sub-query)"; it has to be
    "WHERE EXISTS (sub-suery)" or
    "WHERE (sub-query) = some_value" or
    "WHERE some_value IN (sub_query)", or something similar. WHERE can never be used without some kind of comparison operator, such as EXISTS, = or IN.
    SELECT table.a INNER JOIN table.b ON ...Here are some more syntax errors. The correct syntax for any query is
    SELECT  column_list
    FROM    table_name ...If table.a is your (first) table name, then you're missing the list of columns to SELECT, and the mandatory keyword FROM.
    (table.a.COMPANY = table.b.COMPANY) AND (table.a.PO_NUMBER =table.b.PO_NUMBER) AND (table.a.PO_RELEASE =table.b.PO_RELEASE) AND (table.a.PO_CODE =table.b.PO_CODE) AND (table.a_STATUS=1) AND (table.b.CLOSED_FL = 'Y'));Some general advice about UPDATE:
    If it's not obvious how to use UPDATE to do what you want, then there's a good chance that UPDATE is the wrong tool for the job. MERGE might be much simpler, and more efficient as well. This is especially likely if you need to join the table that's being updated to some other table.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. That way, the people who want to help you can re-create the problem and test their ideas.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
    If you're asking about a DML statement, such as UPDATE, the CREATE TABLE and INSERT statements should re-create the tables as they are before the DML, and the results will be the contents of the changed table(s) when everything is finished.
    Always say which version of Oracle you're using (for example, 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    Edited by: Frank Kulash on Jan 17, 2013 4:58 PM

  • Error in UPDATE statement with SET and JOIN

    Hi
    UPDATE lms_assessment_student QS JOIN lms_assessment_student_ans QA ON QS.pk_Assessment_Stud_Id = QA.fk_Assessment_Stud_Id SET QA.Mark = 1, QA.Comment_Field = 1 WHERE QS.pk_Assessment_Stud_Id = 1 AND QA.Question_Id = 1;
    The above statement when executing is showing ORA-00971: missing SET keyword. so i changed it to
    UPDATE lms_assessment_student QS SET QA.Mark = 1, QA.Comment_Field = 1 WHERE QS.pk_Assessment_Stud_Id = 1 AND QA.Question_Id = 1 JOIN lms_assessment_student_ans QA ON QS.pk_Assessment_Stud_Id = QA.fk_Assessment_Stud_Id ;
    and it showing ORA-00933: SQL command not properly ended.So can anyone help me in solving this problem
    Thanking you in advance
    Dinny

    Hi ,
    So many errors
    YOUR QUERY :
    UPDATE lms_assessment_student QS SET QA.Mark = 1, QA.Comment_Field = 1 WHERE QS.pk_Assessment_Stud_Id = 1 AND QA.Question_Id = 1 JOIN lms_assessment_student_ans QA ON QS.pk_Assessment_Stud_Id = QA.fk_Assessment_Stud_Id ;
    and it showing ORA-00933: SQL command not properly ended.So can anyone help me in solving this problem
    first thing u want to update qa and u write update QS ??
    Second y do u want to join??? just put the condition
    SOLUTION
    UPDATE lms_assessment_student_ans
    SET lms_assessment_student_ans.Mark = 1,
    lms_assessment_student_ans.Comment_Field = 1
    WHERE lms_assessment_student.pk_Assessment_Stud_Id = 1
    AND lms_assessment_student.pk_Assessment_Stud_Id = QA.fk_Assessment_Stud_Id
    Hope it works for u..
    Bhavesh

  • Update statement with CASE and banding

    Hello Folks,
    I am stuck and am going nowhere.
    I have two tables
    MinuteCategory
    Minute
    MinuteCategory
    MinuteLookup
    MinuteCategoryId (surrogate key)
    MinuteLow
    MinuteHigh
    MinuteCategory
    Sample from Minute Lookup table ..
    1 1
    15 <15 min
    2 16
    30 <30 min
    3 31
    45 <45 min
    4 46
    60 <60 minutes
    5 61
    75 <1 hour 15 minutes
    I am trying to update the MinuteCategory column in the MinuteCategory table using the MinuteLookup table.
    For example if the minute = 33 then the corresponding lookup value would be 3 (from the lookup table), because the 
    33rd minute falls in between 31 min and 45 min and the corresponding surrogate key is 3
    Is this possible with an Update statement in SQL? The only thing i can think of is use case statement as the join key between
    the two tables but i don't think it's going to work :(
    UPDATE
    SET MinuteCategory = ml.MinuteCategoryId
    FROM MinuteCategory mc join MinuteLookup ml on mc.Minute = 
    CASE WHEN mc.Minute between ml.MinuteLow and ml.MinuteHigh THEN ml.MinuteCategoryId ELSE NULL
    END
    Would appreciate any help.
    SS

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I have two tables <<
    Have you read any book on data, so you have some idea what a “<something>_category” means? THINK!! A minute is unit of temporal measurement. By definition, it cannot be a category. 
    There is no such thing as a “<something>_category_id”; a data element is a “<something>_category” or a “<something>_id”, as per basic data modeling. 
    Use a table of time slots set to one more decimal second of precision than your data. You can now use temporal math to add it to a DATE to TIME(1) get a full DATETIME2(0). Here is the basic skeleton. 
    CREATE TABLE Timeslots
    (slot_start_time TIME(1) NOT NULL PRIMARY KEY,
     slot_end_time TIME(1) NOT NULL,
     CHECK (start_time < end_time));
    INSERT INTO Timeslots  --15 min intervals
    VALUES ('00:00:00.0', '00:14:59.9'),
    ('00:15:00.0', '00:29:59.9'),
    ('00:30:00.0', '00:44:59.9'),
    ('00:45:00.0', '01:00:59.9'), 
    ('23:45:00.0', '23:59:59.9'); 
    Here is the basic query for rounding down to a time slot. 
    SELECT CAST (@in_timestamp AS DATE), T.start_time
      FROM Timeslots AS T
     WHERE CAST (@in_timestamp AS TIME)
           BETWEEN T.slot_start_time 
               AND T.slot_end_time;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Dynamic UPDATE statement with parameters for column names.

    Hello,
    On this* website I read "The SQL string can contain placeholders for bind arguments, but bind values cannot be used to pass in the names of schema objects (table or column names). You may pass in numeric, date, and string expressions, but not a BOOLEAN or NULL literal value"
    On the other hand, in this Re: execute immediate with dynamic column name update and many other
    posts people use EXECUTE IMMEDIATE to create a dynamic UPDATE statement.
    dynSQL:='UPDATE CO_STAT2 CO SET CO.'||P_ENT_B_G_NAME||' = '||P_ENT_E_G_WE||'
    WHERE ST IN
    (SELECT ST FROM STG_CO_STAT2_TEST CO WHERE
    '||P_ST||' = CO.ST AND
    CO.'||P_ENT_E_G_NAME||' > '||P_ENT_E_G_WE||' AND
    CO.'||P_ENT_B_G_NAME||' < '||P_ENT_E_G_WE||');';
    EXECUTE IMMEDIATE dynSQL ;
    Since this statement is part of a Stored Procedure, I wont see the exact error but just get a ORA-06512.
    The compiling works fine and I use Oracle 11g.
    http://psoug.org/definition/EXECUTE_IMMEDIATE.htm

    OK I extracted from all of your posts so far that I have to use "bind-variables with :"
    From all the other tuorials and forums posts, I assume using the pipe is correct so I added those as well into the script:
    set serveroutput on format wraped;
    DECLARE
    dynSQL VARCHAR2(5000);
    P_ENT_E_G_NAME VARCHAR2 (100) :='test1'; P_ENT_E_G_WE VARCHAR2 (100) :='01.02.2012'; P_ENT_B_G_NAME VARCHAR2 (100) :='01.01.2012';
    P_ST                VARCHAR2 (100) :='32132';
    BEGIN
    dynSQL:= 'UPDATE CO_STAT2 CO SET CO.'||:P_ENT_B_G_NAME||' = '||:P_ENT_E_G_WE||'
                  WHERE ST IN (SELECT ST FROM STG_CO_STAT2_TEST CO WHERE
                  '||:P_ST||'                           = CO.ST                  AND
                  CO.'||:P_ENT_E_G_NAME||'     > '||:P_ENT_E_G_WE||' AND
                  CO.'||:P_ENT_B_G_NAME||'    
    < '||:P_ENT_E_G_WE||')';
    --this is somehow missing after the last < '||:P_ENT_E_G_WE||')';
    dbms_output.enable;
    dbms_output.put(dynSQL);
    --EXECUTE IMMEDIATE dynSQL;    
    END;Problem:I think I figured it out, the dates that I parse into the query need additional '

  • Updating a column from other table

    Hi all,
    I have a simple update query problem. I have four tables
    activist(activist_id,first_name,last_name,c_state),
    membership(activist_id,g_n_id),
    group_network(g_n_id,g_n_type_id),
    school_grop_det(g_n_id,state). For some records in activist table the c_state column is null, i want to update that column with state column of school_group_det table.
    Here is the query for the states which are null
    select distinct a.activist_id,a.first_name,a.last_name,
    a.c_state,sd.state from activist a,membership m,
    group_network g,school_group_det sd where
    a.activist_id=m.activist_id and g.g_n_id=m.g_n_id and
    g.g_n_id=sd.g_N_id and a.c_state is null and g.g_n_type_id='1001'
    order by a.activist_id
    I got the activist_id,first_name,last_name,c_state from activist and state from school_group_det. now i as i told you want to update the c_state with state column of school_group_Det table.
    Pleae any one help me
    Thanks
    Srinivas

    For ur query the reply whay u have got is correct one. For further quries similar to one u had u can download a tool named TOAD (Tools for Oracle Application Developer) from quest site (www.quest.com). Install it a proceed.
    Do let me know how and what u feek about TOAD.

  • Update Statement With Decode and Business Dates

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

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

  • Update statement with Aggregate function

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

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

  • Update statement with Case

    Hi,
    I need to construct an SQL Update statement that uses a case statement.
    I was able to construct one:
    UPDATE tableB
    SET col1 = CASE WHEN (0, 0) = (SELECT col1, col2
    FROM tableA
    WHERE <tableA constraints> )
    THEN "this value"
    ELSE "that value"
    END
    WHERE <tableB constraints>;
    But what I need to do now is to have some comparison inside the CASE WHEN statement, like:
    UPDATE tableB
    SET col1 = CASE WHEN (SELECT col1 from tableA WHERE <tableA constraints> > 0
    AND
    SELECT col2 from tableA WHERE <tableA constraints> > 0
    THEN "this value"
    ELSE "that value"
    END
    WHERE <tableB constraints>;
    Basically, the case would need to pass two (or more) constraints before updating the valuefor tableB.
    By the way, I was able to do this with just one constraint inside the case statement, but I need to pass more than one constraint inside the case.
    Your inputs would be highly appreciated. Thanks.
    Regards,
    Edited by: BatutaBunsing on Jul 22, 2009 6:42 PM

    Example Test
    UPDATE emp
    SET    ename = CASE
                     WHEN (SELECT 1
                           FROM   dual
                           WHERE  1 = 1) > 0 --// condition TRUE
                          AND (SELECT 1
                               FROM   dual
                               WHERE  1 = 1) > 0  --// condition TRUE
                     THEN 'this value'
                     ELSE 'that value'
                   END
    WHERE  empno = 7369
    1 row updated.
    SQL> select * from emp ;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 this value CLERK           7902 17-DEC-80        800                    99
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
    UPDATE emp
    SET    ename = CASE
                      WHEN (SELECT 1
                            FROM   dual
                            WHERE  1 = 2) > 0 --// condition FALSE
                           AND (SELECT 1
                                FROM   dual
                                WHERE  1 = 1) > 0 --// condition TRUE
                      THEN 'this value'
                      ELSE 'that value'
                    END
    WHERE  empno = 7369
    1 row updated.
    SQL> select * from emp ;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 that value CLERK           7902 17-DEC-80        800                    99
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
    ...SS

  • Update statement with nested selects and alias usage

    Hello, we are trying to build an update statement like this...
    update table1 t1
    set attr1 = ( select someattr
    from (nested select 1) as aux1
    (nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
    where some_join_clauses
    where t1.attr2 = 123
    and t1.attr3 = 'abc'
    Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!

    mauramos wrote:
    Hello, we are trying to build an update statement like this...
    update table1 t1
    set attr1 = ( select someattr
    from (nested select 1) as aux1
    (nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
    where some_join_clauses
    where t1.attr2 = 123
    and t1.attr3 = 'abc'
    Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!You can only reference elements nested 1 level deeper in a correlated update statement.
    I'd suggest you try with the MERGE statement, or alternatively, post some sample data (insert statements) and table DDL (create statements), with an 'expected output' description and we can try to help you build a suitable statement.

Maybe you are looking for