Updates using single SQL Update statement.

Hi Guys,
I had an interview... and was not able to give an answer of one of the question.
Given the emp table... need to update the salary with following requirement using one SQL statement...
1. Update salary+1000 for those employees who have salary between 500 and 1000
2. Update salary+500 for those employees who have salary between 1001 and 1500
Both above requirement should be done by using only one SQL update statement... can some one tell me how to do it?

update emp
  set salary   = case when salary between 500 and 1000
                            then salary + 1000
                            when salary between 1001 and 1500
                            then salary + 500
                      end;Regards
Arun

Similar Messages

  • Multi Row update using pl/sql anonymous block process

    Does anyone have an example of multi row update using a pl/sql anonymous block process?
    The reason I can not use the apex mru process is that the table in questions has a five field key.
    My attempts have failed with a bad number.
    Thanks,
    Gary

    Hi Gary,
    can y<ou pls send the definition of thet table and the UPDATE sql.
    It is a littel difficult like this.
    We need more info.
    BR,
    Lutz
    =;-)

  • Insert twice using single sql

    Hi,
    I want to achieve
    1. insert into t1 select col1,'a',col2 from t2;
    2. insert into t1 select col1,'b',col2 from t2;
    using a single sql.
    Thanks..

    Hi,
    Does this work for you?
    SQL> INSERT ALL
      2  INTO t1 VALUES(c1, 'a', c3)
      3  INTO t1 VALUES(c1, 'B', c3)
      4  SELECT * FROM t2;
    2 rows created.
    Elapsed: 00:00:00.00
    SQL> SELECT * FROM t1;
            C1 C2                                                                                                                               C3
             1 a                                                                                                                                 2
             1 B                                                                                                                                 2
    Elapsed: 00:00:00.00Lukasz

  • How to convert the following FORALL Update to direct SQL UPDATE statement

    I have a FORALL loop to update a table. It is taking too long. I want to rewrite the code to a direct UPDATE sql. Also, any other tips or hints which can help run this proc faster?
    CURSOR cur_bst_tm IS
    SELECT listagg(tm, ' ') WITHIN GROUP(ORDER BY con_addr_id) best_time,
           con_addr_id
       FROM   (select Trim(Upper(con_addr_id)) con_addr_id,
                      ||decode(Initcap(start_day),
                                      'Monday', 'm',
                                    'Tuesday', 'tu',
                                    'Wednesday', 'w',
                                    'Thursday', 'th',
                                    'Friday', 'f',
                                     Initcap(start_day))
                      ||'='
                      ||trunc(( ( TO_DATE(start_tm,'HH12:MI:SS PM') - trunc(TO_DATE(start_tm,'HH12:MI:SS PM')) ) * 24 * 60 ))
                      ||','
                      ||trunc(( ( TO_DATE(end_tm,'HH12:MI:SS PM') - trunc(TO_DATE(end_tm,'HH12:MI:SS PM')) ) * 24 * 60 )) tm
               FROM   (SELECT DISTINCT * FROM ODS_IDL_EDGE_OFFC_BST_TM)
                 WHERE con_addr_id is not null)
      GROUP  BY con_addr_id
      ORDER BY con_addr_id;
    TYPE ARRAY IS TABLE OF cur_bst_tm%ROWTYPE;
    l_data ARRAY;
    BEGIN
    OPEN cur_bst_tm;
         LOOP
        FETCH cur_bst_tm BULK COLLECT INTO l_data LIMIT 1000;
        FORALL i IN 1..l_data.COUNT
          UPDATE ODS_CONTACTS_ADDR tgt
          SET best_times = l_data(i).best_time,
          ODW_UPD_BY = 'IDL - MASS MARKET',
           ODW_UPD_DT = SYSDATE,
          ODW_UPD_BATCH_ID = '0'
          WHERE Upper(edge_id) = l_data(i).con_addr_id
           AND EXISTS (SELECT 1 FROM ods_idl_edge_cont_xref src
                       WHERE tgt.contacts_odw_id = src.contacts_odw_id
                          AND src.pc_flg='Y')  
        EXIT WHEN cur_bst_tm%NOTFOUND;
        END LOOP;
      CLOSE cur_bst_tm;Record count:-
    select count(*) from
    ODS_IDL_EDGE_OFFC_BST_TM;
    140,000
    SELECT count(*)
    FROM ods_idl_edge_cont_xref src
    WHERE src.pc_flg='Y';
    118,000
    SELECT count(*)
    FROM ODS_CONTACTS_ADDR;
    671,925
    Database version 11g.
    Execution Plan for the update:
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    UPDATE STATEMENT Optimizer Mode=ALL_ROWS          6 K          8120                     
    UPDATE     ODW_OWN2.ODS_CONTACTS_ADDR                                   
    HASH JOIN SEMI          6 K     256 K     8120                     
    TABLE ACCESS FULL     ODW_OWN2.ODS_CONTACTS_ADDR     6 K     203 K     7181                     
    TABLE ACCESS FULL     ODW_OWN2.ODS_IDL_EDGE_CONT_XREF     118 K     922 K     938
    Edited by: user10566312 on May 14, 2012 1:07 AM

    The code tag should be in lower case like this {noformat}{noformat}. Otherwise your code format will be lost.
    Here is a update statementupdate ods_contacts_addr tgt
    set (
              best_times, odw_upd_by, odw_upd_dt, odw_upd_batch_id
         ) =
              select best_time, odw_upd_by, odw_upd_dt, odw_upd_batch_id
              from (
                   select listagg(tm, ' ') within group(order by con_addr_id) best_time,
                        'IDL - MASS MARKET' odw_upd_by,
                        sysdate odw_upd_dt,
                        '0' odw_upd_batch_id,
                        con_addr_id
                   from (
                             select Trim(Upper(con_addr_id)) con_addr_id,
                                  ||decode(Initcap(start_day), 'Monday', 'm', 'Tuesday', 'tu', 'Wednesday', 'w', 'Thursday', 'th', 'Friday', 'f', Initcap(start_day))
                                  ||'='
                                  ||trunc(((TO_DATE(start_tm,'HH12:MI:SS PM')-trunc(TO_DATE(start_tm,'HH12:MI:SS PM')))*24*60 ))
                                  ||','
                                  ||trunc(((TO_DATE(end_tm,'HH12:MI:SS PM')-trunc(TO_DATE(end_tm,'HH12:MI:SS PM')))*24*60)) tm
                             FROM (
                                  select distinct * from ods_idl_edge_offc_bst_tm
                             WHERE con_addr_id is not null
                   group
                   by con_addr_id
              where upper(tgt.edge_id) = con_addr_id
    where exists
              SELECT 1
              FROM ods_idl_edge_cont_xref src
              WHERE tgt.contacts_odw_id = src.contacts_odw_id
              AND src.pc_flg='Y'
    and exists
              select null
              from (
                   SELECT listagg(tm, ' ') WITHIN GROUP(ORDER BY con_addr_id) best_time,
                        'IDL - MASS MARKET' odw_upd_by,
                        SYSDATE odw_upd_dt,
                        '0' odw_upd_batch_id,
                        con_addr_id
                   FROM (
                             select Trim(Upper(con_addr_id)) con_addr_id,
                                  ||decode(Initcap(start_day), 'Monday', 'm', 'Tuesday', 'tu', 'Wednesday', 'w', 'Thursday', 'th', 'Friday', 'f', Initcap(start_day))
                                  ||'='
                                  ||trunc(((TO_DATE(start_tm,'HH12:MI:SS PM')-trunc(TO_DATE(start_tm,'HH12:MI:SS PM')))*24*60 ))
                                  ||','
                                  ||trunc(((TO_DATE(end_tm,'HH12:MI:SS PM')-trunc(TO_DATE(end_tm,'HH12:MI:SS PM')))*24*60)) tm
                             FROM (
                                  SELECT DISTINCT * FROM ODS_IDL_EDGE_OFFC_BST_TM
                             WHERE con_addr_id is not null
                   GROUP
                   BY con_addr_id
              where upper(tgt.edge_id) = con_addr_id
    This is an untested code. If there is any syntax error then please fix it and try.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to find a dependent row in the all tables using single SQL query

    hi all,
    I have created some table with master and some dependent tables.I want to mark a (row)tuple as inactive in master so that corresponding child records also should be marked as inactive.
    So i decided to mark the master and dependent records as inactive starting from master table and traverse to child tables.
    So I need SQL query to fetch all dependend records to the row(marked row in the master ) from the master table and dependent rows from the child row and to mark as flag inactive.
    can anybody help me out to build this query or any other way to mark flag as inactive ?
    Regards
    punithan

    You can find dependant tables from ALL_CONSTRAINTS, e.g:
    SQL> CREATE TABLE m (id INT PRIMARY KEY, flag VARCHAR2(1) NOT NULL);
    Table created.
    SQL> CREATE TABLE d1 (m_id REFERENCES m, flag VARCHAR2(1) NOT NULL);
    Table created.
    SQL> CREATE TABLE d2 (m_id REFERENCES m, flag VARCHAR2(1) NOT NULL);
    Table created.
    SQL> SELECT table_name, owner, status
      2  FROM   all_constraints c
      3  WHERE  c.constraint_type = 'R'
      4  AND    ( c.r_owner, c.r_constraint_name ) IN
      5         ( SELECT owner, constraint_name
      6           FROM   user_constraints
      7           WHERE  table_name = 'M'
      8           AND    constraint_type IN ('U','P') );
    TABLE_NAME                     OWNER                          STATUS
    D2                             WILLIAMR                       ENABLED
    D1                             WILLIAMR                       ENABLED
    2 rows selected.There is no SQL command to apply all updates in one go, if that's what you were looking for.
    AFAIK the word "tuple" is for mathematics and relational theory, and does not refer to a physical row in a database.

  • Using the software update created problems

    Ok so I bought Leopard and upgraded from Tiger, then updated using the software update. Now I have a whole bunch of problems. My Apple Works is now missing, the program is just gone. All my Adobe programs now give me the error of Incompatible with current OS or some Your Licensing is not working error. I have a whole load of Adobe programs that should be working, like Contribute CS 3 and Photo Shop and Illustrator and Designer and so on. All of which worked under the 4.11 and the 5.1 OSes but now no longer work. This isn't even touching on the elimination of the Classic environment which i have a lot of programs that will cost way too much money to buy again for the new OS.
    Anybody know how to get back Apple Works and how to get the Adobe products running again?

    First set of problems, I had two software packaged programs go missing. Totally erased from the system. iWeb and Apple Works.
    This would not happen after a software update, unless the directory got damaged somehow*:
    http://www.macmaps.com/directoryfaq.html
    That would give the machine a difficult time trying to find files on the computer.
    Next set of problems my external firewire drive stopped being seen from the system.
    This most commonly happens if a Firewire hard drive does not have the proper firmware to be used with the operating system in question. This is one reason most people recommend dismounting and disconnecting all third party devices before applying updates. This used to be a more common problem with 10.3, but not out of the realm of experience of people with 10.5.
    The next most common cause is the clock battery dying, but not quite dead. Replacing it can fix that problem as well.
    I should say that my system consists of several computers networked together.
    I would have completely disconnected the computers before applying the update.
    I can take my external firewire back up time machine drives and connect them to a PC and see the data. But my macs do not even recognise them, they don't even show up when plugged in.
    This is further evidence the firmware on the hard drive was not yet updated for compatibility with the operating system.
    Third set of problems, all the apple install disks became unreadable by my system.
    This can be commonly caused by a dying optical drive, or bad permissions on the system, or a dying clock battery.
    Fourth set of problems, all the Adobe programs became un-useable and returned errors. Adobe has been working with me on this and have been far more helpful than Apple has been.
    That's a case of corrupt files, or files which were migrated from another system. Migration that is done improperly from a PowerPC to an Intel system may create issues with powerpc plugins on an Intel Mac. If your hard drive got over 85% full and/or the directory was damaged for any reason (especially forced reboots), that can also trigger such a reaction during an update.
    Fifth set of problems just recently discovered, all my stored movies, music and podcast in iTunes is gone.
    This is usually due to a directory issue, but can also be a dying hard drive issue.
    Sounds like you have multiple symptoms pointing towards a few common possible causes. Directory damage, and clock battery malfunctioning, and needing a better firmware on your Firewire hard drive case. Replacing the hard drive case with a compatible one is simple enough. http://www.macsales.com/ makes the right cases. I would not go with LaCie, Western Digital, or Seagate cases. Western Digital and Seagate internal hard drives are fine in of themselves. Replace the MyBook hard drive cases with http://www.macsales.com/ cases and same with the LaCies.
    I have Apple TV and EYE TV and a Midi interface box attached to my G5 mac. My G5 is the one that lost Apple Works and iWeb.
    Remove the Midi interface box. It may help things work better.
    My systems have the super drive on them and I have virtual PC and Softwindows installed.
    Softwindows barely works if at all under Classic, and VirtualPC only works with version 7.0.2 under Leopard. If you got an earlier version working under Leopard you were lucky. You really needed to migrate to a supported emulator under Leopard listed on my FAQ*:
    http://www.macmaps.com/macosxnative.html#WINTEL
    It says you didn't research your options well enough before upgrading to Leopard. This has been well documented in the forums before this.
    Booted up from the Norton disks and repaired disk.
    This is the biggest flaw in your plans, which caused ALL your problems. Norton is not compatible with any version of Mac OS X. It eats directories for breakfast, lunch, and dinner. Only Alsoft Disk Warrior is safe and only after a data recovery attempt with Prosoft Data Rescue II, Subrosasoft Filesalvage, or Boomerang's Boomerang. We have constantly harped on the forums here that Norton is damaging to data. This has been known about since Mac OS X came out. It has even been called "Norton Kevorkian" by some.
    You can't blame Apple for this. Your lack of research and lack of asking in the right places at the right time led to your failures.
    - * Links to my pages may give me compensation.

  • Decline and update using SCCM 2012

    On WSUS you can search and update and then decline not required updates.
    There is a way to Decline updates using the Software Update Rol on SCCM 2012?
    I need to hide some unnecesary updates from the SCCM-SoftwareUpdate view, and I can't do it by using the filtering options that comes with this view.
    Any ideas?
    Thank you for your help.

    No. There is explicit way to decline an update and no real reason to either. If you need to, you can create a sub-folder under the All Update node and move the un-wanted updates there.
    Jason | http://blog.configmgrftw.com

  • Compare and insert in single SQL

    Hi ,
    I want to insert data from one source table to destination table based on the condition that a row does not exist in destination table based on some column filter . Is it achievable using single SQL.?
    Merge statement cannot be used as there is no unique key in source table and destination table.
    Here is the data and tables.
    create table test_source
    x_id number,
    report_sent_flag varchar2(30),
    year number
    insert into test_source
    select 10 , 'Y' , 2013 from dual
    union all
    select 20 , 'Y' , 2013 from dual
    union all
    select 30 , 'Y' , 2013 from dual
    union all
    select 10 , 'Y' , 2013 from dual
    union all
    select 20 , 'Y' , 2013 from dual
    union all
    select 30 , 'Y' , 2013 from dual;
    create table test_dest
    x_id number,
    report_sent_flag varchar2(30),
    year number
    insert into test_dest
    select 10 , 'Y' , 2013 from dual
    union all
    select 10 , 'Y' , 2013 from dual;
    select * from test_source  ;
    10    Y    2013                                            
    10    Y    2013
    20    Y    2013
    20    Y    2013
    30    Y    2013
    30    Y    2013
    select * from test_dest ;
    10    Y    2013
    10    Y    2013
    Now , i need compare test_source and test_dest tables on column  (x_id , report_sent_flag and year ) column , since 10 , Y , 2013 is present in test_dest , it will be skipped . Rest should get inserted into test_dest table from test_source.
    Can it done by SQL only ?
    Please assist
    Thanks
    Please assist

    only SQL :
    SQL> select * from test_source  ;
          X_ID REPORT_SENT_FLAG                     YEAR
            10 Y                                    2013
            20 Y                                    2013
            30 Y                                    2013
            10 Y                                    2013
            20 Y                                    2013
            30 Y                                    2013
    6 rows selected
    SQL> select * from test_dest ;
          X_ID REPORT_SENT_FLAG                     YEAR
            10 Y                                    2013
            10 Y                                    2013
    SQL> select * from log_exists_records;
          X_ID REPORT_SENT_FLAG                     YEAR
    SQL>
    SQL> insert into log_exists_records
      2  select * from test_source
      3  where (x_id,report_sent_flag,year ) in (select x_id,report_sent_flag,year from test_dest)
      4  /
    2 rows inserted
    SQL>
    SQL> insert into test_dest
      2  select * from test_source
      3  where (x_id,report_sent_flag,year ) not in (select x_id,report_sent_flag,year from test_dest)
      4  /
    4 rows inserted
    SQL> select * from test_source  ;
          X_ID REPORT_SENT_FLAG                     YEAR
            10 Y                                    2013
            20 Y                                    2013
            30 Y                                    2013
            10 Y                                    2013
            20 Y                                    2013
            30 Y                                    2013
    6 rows selected
    SQL> select * from test_dest ;
          X_ID REPORT_SENT_FLAG                     YEAR
            20 Y                                    2013
            30 Y                                    2013
            20 Y                                    2013
            30 Y                                    2013
            10 Y                                    2013
            10 Y                                    2013
    6 rows selected
    SQL> select * from log_exists_records;
          X_ID REPORT_SENT_FLAG                     YEAR
            10 Y                                    2013
            10 Y                                    2013
    SQL>
    Ramin Hashimzade

  • OTA Update Not Querying Custom Update URL

    I built Firefox 2.0 for the Nexus 4 and it does not check for updates using my custom update URL. The phone just sits on "Checking for updates..." My webserver logs also show there is no request for update.xml. Is this functionality missing? Can it be enabled by me?

    2.0 isn't completely ready yet and obviously there are bugs... I'm not sure what's going on the issue you are having but the "Join the Firefox OS Community" at the bottom of this [https://developer.mozilla.org/en-US/Firefox_OS page] has some contact info so you can reach out to get some assistance with the issue you are having.
    I'm not sure if stackoverflow helps but you can try posting there too!

  • Lync Standard Edition Server pairing -- Archiving and monitoring collocated but Single SQL backend

    Hi,
    I have a scenario where in ---we have Two Standard Edition Servers ( SE1 and SE2) with 1K users each ( Total 2K in one Site) paired to enable High Availability. The Standard Edition Server has archiving and monitoring and mediation server collocated.
    For archiving + monitoring database we have a Seperate SQL enterprise edition server.
    Quetions:
    1. Can we use single SQL Enterprise Edition as backend for (archiving and monitoring ) for both SE1 and SE2 ?
    2. If yes, do we need two seperate instances?
    3. If not, could you please suggest the best possible solution in such an environment ?
    Regards,
    Archana Rao

    Hi ArchanaVR,
    Agree with Michael, and add some more details.
    By default, the SQL Server Express back-end database is collocated on the Standard Edition server. You cannot move it to a separate computer. With one exception, you cannot collocate other databases on the Standard Edition server. If you choose to deploy
    Persistent Chat Server on a Standard Edition server, you can collocate the Persistent chat database and the Persistent Chat Compliance database on the same Standard Edition server.
    You can collocate each of the following databases on a single database server:
    Monitoring database
    Archiving database
    A back-end database for an Enterprise Edition Front End pool
    You can collocate any or any or all of these databases in a single SQL instance or use a separate SQL instances for each, with the following limitations:
    Each SQL instance can contain only a single back-end database (for an Enterprise Edition Front End pool), single Monitoring database, single Archiving database, single persistent chat database, and single persistent chat compliance database.
    The database server cannot support more than one Enterprise Edition Front End pool, one server running Archiving, one server running Monitoring, single Persistent Chat database, and single Persistent Chat compliance database, but it can support one of each,
    regardless of whether the databases use the same instance of SQL Server or separate instances of SQL Server.
    http://technet.microsoft.com/en-us/library/gg398131.aspx
    Best regards,
    Eric

  • Use of ROWID in SQL Update Statement

    Hi All,
    I have an update statement which uses the rowid column to perform the selection on the target table. Given that a rowid represents the physical location of a row on disk we know that this reference can change when various activities are performed on the database/table/row etc...
    Here is an example of the statement I am issuing:
    UPDATE tabA outertab SET col1 = 'Value'
    WHERE EXISTS (SELECT 1 FROM tabA innertab WHERE outertab.ROWID = outertab.ROWID AND ...)
    Obviously the inner query is more complicated and uses other tables etc... but for the purposes of the example we dont need to include the detail.
    My question is: When using rowid in a single SQL statement as a reference from a subquery to the outer statement is there a risk that external activities can change the rowid and those changes be reflected within the database session that my query is executing thus causing an inconsistency between the inner and outer SQL clause?
    In response to the question which will follow this post: "Why don't you just use a PK", We would like to avoid maintaining a PK on the table as we are talking about very large volumes of data and we dont want to have to issue a call to a sequence if we can avoid it when we are inserting the data. If however there is a risk that this Update statement could fail or update the wrong rows then we may have to use a PK.
    I know there is a lot of threads about this but I havnt been able to find one that someone has answered with any kind of confidence or clarity, any help would be much appreciated.
    Thanks
    Keith
    Edited by: The Turtle on Mar 5, 2009 5:24 AM

    When using rowid in a single SQL statement as a reference from a subquery to the outer statement is there a risk that external activities can change the rowid and those changes be reflected within the database session that my query is executing thus causing an inconsistency between the inner and outer SQL clause?No, it's safe to use rowid in this type of query. Docs
    A row's assigned rowid remains unchanged unless the row is exported and imported using the Import and Export utilities. When you delete a row from a table and then commit the encompassing transaction, the deleted row's associated rowid can be assigned to a row inserted in a subsequent transaction.

  • SQL Update a Single Row Multiple Times Using 2 Data Sets

    I'm working in tsql and have an issue where I need to do multiple updates to a single row based on multiple conditions. 
    By Rank_
    If the column is NULL I need it to update no matter what the Rank is.
    If the Ranks are the same I need it to update in order of T2_ID.
    And I need it to use the last updated output.
    I've tried using the update statement below but it only does the first update and the rest are ignored. Here is an example of the data sets i'm working w/ and the Desired results. Thanks in advance!
    update a
    set Middle = case when a.Rank_> b.Rank_ OR a.Middle IS NULL then ISNULL(b.Middle,a.Middle) end,
    LName = case when a.Rank_> b.Rank_ OR a.Lname IS NULL then ISNULL(b.LName,a.LName) end,
    Rank_ = case when a.Rank_> b.Rank_ then b.Rank_ end
    from #temp1 a
    inner join #temp2 b on a.fname = b.fname
    where b.T2_ID in (select top 100% T2_ID from #temp2 order by T2_ID asc)

    The Merge clause actually errors because it attempt to update the same record.  I think this CTE statement is the closest I've come but I'm still working through it as I'm not too familiar w/ them.  It returns multiple rows which I will have to
    insert into a temp table to update since the resulting row I need is the last in the table.
    ;WITH cteRowNumber
    AS(
    Select DISTINCT
    Row_Number() OVER(PARTITION BY a.LName ORDER BY a.LName ASC, a.Rank_ DESC,b.T2ID ASC) AS RowNumber
    ,a.FName
    ,a.LName
    ,b.LName as xLname
    ,a.MName
    ,b.MName AS xMName
    ,a.Rank_
    ,b.Rank_ AS xRank
    ,b.T2ID
    FROM #temp1 a
    inner join #temp2 b
    ON a.fname = b.fname
    ), cteCursor
    AS(
    Select a.RowNumber,
    a.Fname
    ,a.LName
    ,a.xLname
    ,a.MName
    ,a.xMName
    ,a.xRank
    ,a.T2ID
    ,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xRank,a.Rank_) else ISNULL(a.Rank_,a.xRank) end AS Alt_Rank_
    ,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xMName,a.MName) else ISNULL(a.MName,a.xMName) end AS Alt_MName
    ,CASE WHEN a.Rank_ >= a.xRank THEN ISNULL(a.xLName,a.lname) else ISNULL(a.LName,a.xlname) end as Alt_Lname
    FROM cteRowNumber a
    where a.RowNumber = 1
    UNION ALL
    Select crt.RowNumber
    ,crt.FName
    ,crt.LName
    ,crt.xLname
    ,crt.MName
    ,crt.xMName
    ,crt.xRank
    ,crt.T2ID
    ,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xRank,Prev.Alt_Rank_) else ISNULL(Prev.Alt_Rank_,crt.xRank) end AS Alt_Rank
    ,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xMName,Prev.Alt_MName) else ISNULL(Prev.Alt_MName,crt.xMName) end AS Alt_MName
    ,CASE WHEN Prev.Alt_Rank_ >= crt.xRank THEN ISNULL(crt.xLName,Prev.Alt_Lname) else ISNULL(Prev.Alt_Lname,crt.xLName) end as Alt_Lname
    FROM cteCursor prev
    inner join cteRowNumber crt
    on prev.fname = crt.fname and prev.RowNumber + 1 = crt.RowNumber
    SELECT cte.*
    FROM cteCursor cte

  • Using UPDATE in complex SQL

    I wonder if anyone can help with an update..
    Image 2 tables: packagetable and parttable
    packagetable has component to part relationships, eg:
    Package Part
    PACK1 PART1
    PACK1 PART2
    PACK2 PART6
    PACK2 PART7
    PACK2 PART9
    PACK3 PART3
    PACK3 PART7
    parttable has parts and their price
    Part Price
    PART1 10
    PART2 8
    PART3 15
    PART6 1
    PART7 5
    PART9 10
    but packages are also stored here as parts and have a price (total of components)
    PACK1 18 (10 + 8)
    PACK2 16 (1 + 5 + 10)
    PACK3 20 (15 + 5)
    The actual tables are more complex and include a site, a discount, a qty per package, etc but you get the gist.
    I need to update package parts so that they equate to the total of their parts because some package parts have the wrong price.
    So I need to say
    PACK1 = price of PART1 + price of PART2
    PACK2 = price of PART6 + price of PART7 + price of PART9
    PACK3 = price of PART3 + price of PART7
    The actual SQL to obtain the resultant price is:
    select
    spp1.parent_part packpart,
    (select sp2.list_price from ifsapp.sales_part sp2 where sp2.catalog_no = spp1.parent_part) Current_price,
    sum((sp1.list_price - (round(sp1.list_price*(spp1.discount_perc/100),2))) * spp1.qty_per_assembly) Proposed_price
    from
    ifsapp.sales_part_package spp1,
    ifsapp.sales_part sp1
    where
    spp1.catalog_no=sp1.catalog_no
    and
    spp1.contract=sp1.contract
    and
    spp1.contract='OIAMN'
    having
    sum((sp1.list_price - (round(sp1.list_price*(spp1.discount_perc/100),2))) * spp1.qty_per_assembly)<9999999
    group by
    spp1.parent_part
    This results in this case are:
    Package Part     Current          Proposed
    123          0.00          4911.90
    124          0.00          23450.00
    126          0.00          23450.00
    128          0.00          23950.00
    133          0.00          26975.00
    134          1200.00          1249.86
    140          0.00          9995.00
    144          0.00          9995.00
    145          0.00          8995.00
    150          9021.00          9994.97
    151          0.00          9994.97
    152          0.00          8994.97
    155          0.00          17895.00
    168          0.00          17095.00
    Clealry the only two values I really need are Package Part and Proposed value... but how can I update the package part prices using a single SQL statement?

    If I interpret your question right,
    merge works for you in 9i and 10G:
    SQL> select * from emps;
    ENAME          DEPTNO       SSAL
    SMITH              20
    ALLEN              30
    WARD               30
    JONES              20
    MARTIN             30
    BLAKE              30
    CLARK              10
    SCOTT              20
    KING               10
    TURNER             30
    ADAMS              20
    JAMES              30
    FORD               20
    MILLER             10
    14 rows selected.
    SQL> select * from sals;
    ENAME             SAL
    SMITH            1000
    ALLEN            1800
    WARD             1450
    JONES            2975
    MARTIN           1250
    BLAKE            2850
    CLARK            2450
    SCOTT            3000
    KING             5000
    TURNER           1500
    ADAMS            1100
    JAMES            1120
    FORD             3000
    MILLER           1300
    14 rows selected.
    SQL> /* In 9i */
    SQL> merge into emps
      2  using (
      3  select e.deptno,sum(s.sal) sm from emps e, sals s
      4  where e.ename = s.ename
      5  group by e.deptno
      6  ) src
      7  on (src.deptno = emps.deptno)
      8  when matched then
      9   update set emps.ssal = src.sm
    10  when not matched then
    11   insert (emps.deptno) values(0)
    12  /
    14 rows merged.
    SQL>/* In 10G */
    SQL> merge into emps
      2  using (
      3  select e.deptno,sum(s.sal) sm from emps e, sals s
      4  where e.ename = s.ename
      5  group by e.deptno
      6  ) src
      7  on (src.deptno = emps.deptno)
      8  when matched then
      9   update set emps.ssal = src.sm
    10  /
    14 rows merged.
    SQL> select * from emps order by deptno;
    ENAME          DEPTNO       SSAL
    CLARK              10       8750
    KING               10       8750
    MILLER             10       8750
    SMITH              20      11075
    ADAMS              20      11075
    FORD               20      11075
    SCOTT              20      11075
    JONES              20      11075
    ALLEN              30       9970
    BLAKE              30       9970
    MARTIN             30       9970
    JAMES              30       9970
    TURNER             30       9970
    WARD               30       9970
    14 rows selected.But it could be better if you changed the structure you were using - you could
    pick out package names and price summary in the separate table -
    now you packagetable looks as the unnormalized structure which is overloaded
    by data.
    Rgds.

  • Update two different tables by a single sql query:

    Hi All,
    i need to update two different talbes in a single sql query..
    i m using the following query
    UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12
    AND
    UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12
    i m getting the following error:
    Odbc driver returned an error (SQLExecDirectW).
    Error Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43093] An error occurred while processing the EXECUTE PHYSICAL statement. [nQSError: 17001] Oracle Error code: 936, message: ORA-00936: missing expression at OCI call OCIStmtExecute: UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12 AND UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12 . [nQSError: 17011] SQL statement execution failed. (HY000)
    SQL Issued: EXECUTE PHYSICAL CONNECTION POOL writeback UPDATE FT_User_Alert SET Subscription = 'W' where product_key=1 and measure_key = 12 AND UPDATE LU_Monthly_Alert_Budget_Sheet SET Min_Red_Range ='16.0' AND Max_Green_Range ='24.0'AND Max_Red_Range ='27.0'AND Min_Green_Range ='16.0' where product_key='1' and measure_key = 12
    but when i m ushin the same query in Microsoft SQL Server it executes properly:
    please help me out...

    Duplicate thread. I've already answered on your other thread...
    update two different tables by a single sql query:

  • Combine select and update into single statement,without bind-variable

    I have a problem, that I think is not possible to solve the way I want to, but I just wanted to check before leaving the idea...
    I am looking for a way to combine the select and the update statement into one single statement. This is what I wan't to achive: select some data, and update the data selected before returning them.
    On this site http://www.psoug.org/reference/update.html I see that the following are possible:
    var bnd1 NUMBER
    var bnd2 VARCHAR2(30)
    var bnd3 NUMBER
    UPDATE employees
    SET job_id ='SA_MAN', salary = salary + 1000,
    department_id = 140
    WHERE last_name = 'Jones'
    RETURNING salary*0.25, last_name, department_id
    INTO :bnd1, :bnd2, :bnd3;
    I need to have this as a single statement, and cannot use bind-variables. So I was hoping that something like this could be possible:
    UPDATE customer c
    SET c.HAS_CREDIT ='1'
    WHERE c.HAS_CREDIT = '0'
    RETURNING c.CUSTOMER_NO, c.FIRSTNAME, c.LASTNAME
    where c.HAS_CREDIT = '1'
    But this doesn't compile, complaining of missing into (ORA-00925: missing INTO keyword). And even though I would like this to be possible because this would solve my current problem, I think it would be very confusing. For instance; would the where clause of the returning part be operating after the update or before?
    Any comments or suggestions on how to get it work in a single statement, or should I just leave this path straight away?

    Hi,
    RETURNING only works with bind variables, see
    http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm#sthref3006
    The real problem is that the form of RETURNING clause with bind variables is only valid for single row update or insert statements.
    To update (or insert) multiple rows and return the data, you will need to use
    RETURNING BULK COLLECT INTO clause. See
    http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/tuning.htm#sthref2236
    Cheers,
    Colin

Maybe you are looking for

  • Setting Up iTunes Library on An External Drive

    I had to reload my brother's new Mac Mini and decided to put his iTunes Libary on a Lacie 500 GB external. I installed Tiger and all of the updates. I went into iTunes preferences and changed the file location of the iTunes folder to the external dri

  • Can I get the photographer's package AND Illustrator?

    I want to subscribe to the Photography Package of Photoshop and Lightroom ($9.99/month).  I'm wondering if later, I can also add on Illustrator with the "one app" offer ($19.99/mo), at some point, thus making my total payment $29.98 for all three pro

  • Layer relative positon to background, width and hight

    Hi All I have a problem in Photoshop: I have a layered image and I wanted to know the relative position of the layer to the background and the width and hight. Does Photoshop allow that? I know you can get the position by moving the mouse cursor to t

  • Error  in posting billing document ( Export Data Missing)

    Hi Gurus, I am facing a unique problem. When I am posting a domestic invoice with reference to service order material Group is LEIS( service withought delivery )  is LEIS, the system is displaying a message Document & has been saved (foreign trade da

  • Copying iTunes library onto new MacBook Pro

    I want to copy my existing iTunes library to my shiny new 13" unibody MacBook Pro. Since my 17" MacBook Pro remains my main home computer I want to leave the library intact on that machine - I just want to copy the library onto the new machine (album