Update with Select top n statement

Hi All,
Can I use update statemet like this..
Update table1
set Name=(select top (100) t2.name from table2 t2 where table1.ID=t2.ID)
Please let me know ASAP its very urgent
Thanks in Advance
RH
sql

Hi sql9 !
You might need below query;
CREATE TABLE Table1 (ID INT,Name VARCHAR(10))
CREATE TABLE Table2 (ID INT,Name VARCHAR(10))
--TRUNCATE TABLE Table1
--TRUNCATE TABLE Table2
INSERT INTO Table1
SELECT 1,'ABC' UNION ALL
SELECT 2,'DEF' UNION ALL
SELECT 3,'GHI'
INSERT INTO Table2
SELECT 1,'JKL' UNION ALL
SELECT 1,'MNO' UNION ALL
SELECT 2,'PQR' UNION ALL
SELECT 2,'STU' UNION ALL
SELECT 3,'VWX' UNION ALL
SELECT 3,'YZ'
UPDATE Table1 SET Name = (SELECT TOP 1 T2.Name FROM Table2 T2 WHERE Table1.ID = T2.ID)
SELECT * FROM Table1
--ID Name
--1 JKL
--2 PQR
--3 VWX
--You can simply re-write your SQL with below query and you don't have to specify TOP Clause inside subquery
UPDATE T1 SET T1.Name = T2.Name
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.ID = T1.ID
SELECT * FROM Table1
--ID Name
--1 JKL
--2 PQR
--3 VWX
Note : In your first query TOP 100 returning more than 1 value from subquery which is not allowed.
Please let me know if this doesn’t work for you. Hope I have answered you correctly.
Thanks,
Hasham

Similar Messages

  • Update with dynamic top value in CTE

    Hi,
    Scenario :
    I have 2 main tables. One is header level and another is detail level. Each header table records have multiple detail entries based on the header table Quantity. Eg: The header have Quantity 50, detail table have 50 receords. Likwise each header table entry
    have Quantity based record count in the detail table.
    My Question:
       User enter multiple header request in one temp table. So that based on the requested quantity the first (FIFO) or top requested number of receords needs to be updated in the detail level. For example, if user enter header 1 and quantity 25.
    Then update the  top 25 records in the detail table on header id is updated.
    HeaderTable Name is ReceiveLot, Detail table is ReceiveSerial and temp table is
    StoresReferenceConsumptions (which is the table users entered the request)
    I wrote the query like below
    ;with cte
    as
    SELECT
    B.ReceiveLotID
    ,CAST(A.Quantity AS INT) Quantity
    FROM StoresReferenceConsumptions A
    INNER JOIN ReceiveLot B
    ON A.ReferenceNumber = B.ReceiveLotID
    WHERE A.ReferenceType=1
    ,cte1
    as (
    SELECT
    B.ReceiveSerialID,
    B.SerialNumber
    FROM cte A
    INNER JOIN ReceiveSerial B
    ON A.ReceiveLotID = B.ReceiveLotID
    WHERE B.[Status] = 'ALLOTTED'
    select * from cte1
    Here i got all the detail table values of he header id which is requested. But i can't use the top with hedaer Quantity in cte1. So how i update only the top number of records.
    If i use general update query i need to use 2 subqueries . please guide me.
    Actualy this is my revised query. My original query is very time consuming because i used cte inside cursor which is creating problems in production. so only i am try like this

    Thanks friend. But the 25 is not static. 25 is the requested quantity from the user which is available in the cte.Quantity.  So for each header entries in the StoresReferenceConsumption  i have entirely different quantity.
    Anyway i basically finished the concept using cursor. Please look into the query from below. Any possiblity like the query in CTE or cursor is better in this case
    DECLARE @ReceiveLotID INT
    DECLARE @LotQuantity NUMERIC(18,4)
    DECLARE updateCursor cursor for
    SELECT
    A.ReceiveLotID
    ,B.Quantity
    FROM ReceiveLot A
    INNER JOIN StoresReferenceConsumptions B
    ON A.ReceiveLotID = B.ReferenceNumber
    WHERE B.ReferenceType=1
    OPEN updateCursor
    FETCH NEXT FROM updateCursor INTO @ReceiveLotID, @LotQuantity
    WHILE @@FETCH_STATUS = 0
    BEGIN
    UPDATE A
    SET [Status] = 'DISPATCHED'
    FROM ReceiveSerial A
    WHERE A.ReceiveSerialID IN
    (SELECT TOP (CAST(@LotQuantity AS INT)) ReceiveSerialID FROM ReceiveSerial
    WHERE ReceiveLotID = @ReceiveLotID AND [Status] = 'ALLOTTED' ORDER BY SerialNumber)
    FETCH NEXT FROM updateCursor INTO @ReceiveLotID, @LotQuantity
    END
    CLOSE updateCursor
    DEALLOCATE updateCursor

  • Update with Select from a non-existant column

    Hello,
    If I have two tables in Oracle database:
    Table_1 has column id, c1, c2
    Table_2 has column id, c1, c2
    If I run the following select statement, it will give error, because column c3 does not exist:
    select c3 from table_2;
    However, if I run the following update statement, it run successfully with error. It shows, for example, 10 rows updated:
    update table_1 t1 set t1.c2 =
    (select t2.c3 from table_2 t2
    where t2.id = t1.id);
    Could someone explain to me what happens?
    Regards!

    rp0428 wrote:
    >
    It's called a Correlated Sub-Query . It's documented, with examples, in the SQL Language manual
    >
    I'm familiar with correlated sub-queries. That link has NO examples using a column in the FROM list of a sub-query that is NOT in a table in the FROM list of that sub-query.
    You can certainly use constants, or functions in a select list without needing a table reference but I haven't seen any documentation showing an example of selecting a column in a sub-query that doesn't exist in one of the FROM tables.There are no examples of selecting a column from the outer query in a sub-query because in 99.999% of the cases it would be the wrong thing to do, however it is possible. Clearly the sub-query can "see" columns in the outer query otherwise how would it see the values for a correlated sub-query. As Frank said, there is nothing in the documenation that precludes using an outer column in the sub-query, and this paragraph from Frank's link certainly seems to pretty generally refer to the entire sub-query:
    If columns in a subquery have the same name as columns in the containing statement, then you must prefix any reference to the column of the table from the containing statement with the table name or alias. To make your statements easier to read, always qualify the columns in a subquery with the name or alias of the table, view, or materialized view.John

  • JDBC Receiver adapter ( INSERT/UPDATE with SELECT)

    Is it possible to have following kind of SQL Statement comming out JDBC Receiver Adatpter. If yes what would be the corresponding XML Document format for this.
    UPDATE suppliers 
    SET supplier_name = ( SELECT customers.name
    FROM customers
    WHERE customers.customer_id = suppliers.supplier_id)
    This condition also needs to be applied for Insert condition. Any pointer would be useful.
    Thanks,
    Samir

    Hi
    Refer this links,
    http://help.sap.com/saphelp_nw04/helpdata/en/22/b4d13b633f7748b4d34f3191529946/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/b0/676b3c255b1475e10000000a114084/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/2e/96fd3f2d14e869e10000000a155106/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/4d/8c103e05df2e4b95cbcc68fed61705/frameset.htm
    Regards,
    Suryanaryana

  • Update with Select

    Hello, I am trying to update all the columns of one table from the records of another table.
    I have managed to do a similar thing using the statement below to insert into table 2 all the rows that exist in table 1 and don't exist in table 2.
    insert into DFO_FACILIDADE
    select IMP.* from DFO_IMPORTADO_OBJECTEL IMP left outer join DFO_FACILIDADE FAC on IMP.FACILIDADE_ID = FAC.FACILIDADE_ID
    where FAC.FACILIDADE_ID is null;I've tried the codes below, but none of them worked:
    update DFO_FACILIDADE FAC set FAC.* = IMP.*
    from DFO_IMPORTADO_OBJECTEL IMP where IMP.FACILIDADE_ID = FAC.FACILIDADE_ID
    update DFO_FACILIDADE F (inner join DFO_IMPORTADO_OBJECTEL I on I.FACILIDADE_ID = F.FACILIDADE_ID)
    set f.facilidade_identificador = i.facilidade_identificador
    update DFO_FACILIDADE set facilidade_identificador = i.facilidade_identificador
    from (select f.facilidade_id from dfo_importado_objectel i, DFO_FACILIDADE f where i.facilidade_id = f.facilidade_id) fac_idIs there a way to do this?
    Thanks,
    Komyg

    Try something like:
    UPDATE DFO_FACILIDADE FAC
    SET FAC.column1 = (SELECT column1
                                    FROM DFO_IMPORTADO_OBJECTEL IMP
                                    WHERE IMP.FACILIDADE_ID = FAC.FACILIDADE_ID),
           FAC.column2 =  (SELECT column2
                                    FROM DFO_IMPORTADO_OBJECTEL IMP
                                    WHERE IMP.FACILIDADE_ID = FAC.FACILIDADE_ID)  ;Regards,
    Miguel

  • Ministore not updating with selection

    iTunes 7.4.1 on Intel Mac (mini or macbook). When I have the Ministore on (visible), and I select a song, the minstore display doesn't update. It used to do what is advertised in earlier versions -- showing related songs; but now it doesn't. Anybody seen this or know what's wrong?

    I've just noticed this difference, too. The mini store doesn't update based on my selection in the song listing. I know it won't for items it doesn't recognize, but I'm selecting items I've bought from the store instead of items from CDs, and the mini store is still not updating.

  • I have a column where I have implemented writeback, its working fine. On top of this I need to show 0 as No and 1 as yes in our report, that is also done. Now I want to enter Yes in a column where it was no and I want database table to get update with 1.

    I have a column where I have implemented writeback, its working fine. On top of this I need to show 0 as No and 1 as yes in our report, that is also done. Now I want to enter Yes in a column where it was no and I want database table to get update with 1. I am not sure how to do it. SOmeone please help me out.

    Hi ,
    In your write back XML  try the below  query insert
    INSERT INTO TABLE_XYZ (attribute1)  values (SELECT CASE  WHEN @{C1}=’Yes’ then 1 when @{C1}=’No’ then 0 else null end from dual)
    Regards
    Rajagopal

  • Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination

    Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination
    Problem in committing transactions in Multiple Forms (Oracle Forms) with POST built-in command:
    Consider that the following statements are written in WHEN-WINDOW-CLOSED trigger of a called form.
    Statements in called form (Form name: FORM_CHILD):
    go_block('display_block') ;
    do_key('execute_query') ;
    -- Data from table_b will be populated in this block, based on the value of COLUMN_1 obtained
    -- from TABLE_A.
    -- Example: If the value of COLUMN_1 is 10, then all the matching records from TABLE_B, which
    -- are inserted with value 10 in TABLE_B.COLUMN_1 will be fetched and shown here.
    if user_choice = 'YES' then
    commit ;
    else
    rollback ;
    end if ;
    Statements in calling forms:
    There are two calling forms having following statements and it is going to call the above said called form.
    CALLING FORM 1
    Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...; Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    CALLING FORM 2:
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...;
    insert into table_b ...;
    Our understanding:
    Assume that both the forms are running from two different machines/instances, issuing commit at the same time. In this case, forms will start executing the statements written in ON-INSERT trigger, the moment POST command is executed. Though the commit is issued at the same time, according to oracle, only one of the request will be taken for processing first. Assume that calling form 1 is getting processed first.
    So, it fetches the value available in COLUMN_1 of TABLE_A and locks the row from further select, update, etc. as SELECT...FOR UPDATE command is used (note that NOWAIT is not given, hence the lock will be released only when COMMIT or ROLLBACK happens) and proceed executing further INSERT statements. Because of the lock provided by the SELECT...FOR UPDATE command, the statements in calling form 2 will wait for the resource.
    After executing the INSERT statements, the FORM_CHILD is called. The rows inserted in to TABLE_A will be queried and shown. The database changes will be committed when user closes the window (as COMMIT is issued in its WHEN-WINDOW-CLOSED trigger). Then the SELECT...FOR UPDATE lock will be released and calling form 2's statements will be executed.
    Actual happenings or Mis-behavior:
    Calling form 2 starts executing INSERT statements instead of waiting for SELECT...FOR UPDATE lock. Also, the value selected from TABLE_A.COLUMN_1 is same in both the calling forms, which is wrong.
    The rows inserted into TABLE_B are having similar COLUMN_1 values in calling form 2 and they are fetched and shown in the called form FORM_CHILD.
    Note that in calling form 2 also POST only is issued, but the changes posted there are accessible in calling form 1 also, which is wrong.
    Kindly suggest us as to how to fix above problem. It will be much use, if you can send us the information regarding the behavior of Oracle Forms POST built-in also.
    Our mail ID: [email protected]
    Thanks a lot in advance.

    You have several problems:
    1. On-Insert will ONLY run if you have created a new record in a base-table block. If you haven't done that, then the POST command will not cause it to run.
    2. Select for update without a "no wait" will lock records for the first form, but when the second form tries this, it will hit the ORA-00054 exception, and will NOT wait. The only way you could make it wait is to issue an UPDATE sql command, which is not such a good way to go.
    All POST does is issues SQL insert or update commands for any changes the user has made to records in a form's base-table blocks, without following with a Commit command.
    Also understand that Commit is the same as Commit_Form, and Rollback is the same as Clear_Form. You should read up on these in the Forms help topics.

  • Creating a Job for publication in Sql Server with select statement for passing a parameter

    I am creating a job for adding article to a publication.  the second step (e.g. for adding article) gives me error. I pass the name of the table as follow:
         EXEC sp_addarticle
               @publication = 'TTB', --THE NAME OF MY PUBLICATION
               'select top (1)' @article = 'Name from TableAdded Order by create_date Desc',
               'select top (1)' @source_object = 'Name from TableAdded Order by create_date Desc',
                @force_invalidate_snapshot = 1;
    TableAdded is a table I have in my publisher which contains the name of the newly added table.
    I believe it fails because the way I pass the name of the article to the store procedure is not correct. Can anyone please help me on that?
    Kind regards
    Amin

    Yes, the way you add article is wrong.
    you may try the below and let us know if you have any issues:
    while loop begin (Get the values from TableAdded with status IsAdded=0)
              Assign the values to variables like @article = Select top 1 Name from TableAdded where IsAdded=0
              Call the sp_addarticle assigning the variable
              update the Isadded flag in tableAdded for the name to 1 
     end while 
    BTB, Article configuration is supposed to be a one time configuration. Having said, you can easily configure through API. Caution, not sure what are you trying here, for adding new article, you may need to synch the data first in the above approach and should
    carried out in the downtime.

  • Prepared Statement, executing  SELECT TOP in Ms Access

    I'm having the following problem. I built an application fetching data without any problem from MS SQL Server, this was using prepared statements. Now i'm having this strange problem with the following query:
    SELECT TOP 1 *
    FROM table
    WHERE appliance_id = ?
    AND ttimestamp_initpk <= ?
    AND ((Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?))
    ORDER BY ttimestamp_initpk DESC
    While on SQL Server this fetches just a record, on MS Access it fetches the whole set of records without worrying about TOP instruction.
    That is, it acts like a SELECT * FROM, and this slows down runtime behaviour.
    I'm using sun.jdbc.odbc.JdbcOdbcDriver, is it the problem?
    Thanks, Mirko

    Thanks for your answer, but i'm not sure this is the reason.
    I made one more test: i wrote a .Net application connecting to a MS Access using an ODBC connection. SELECT TOP statement is working fine, so i think i'll try another JDBC driver. Any other solution??
    Thanks,
    Mirko

  • Trigger with SELECT-FOR-UPDATE

    There is a trigger on a table, which updates a particular column with SYSDATE BEFORE an INSERT OR UPDATE in the table.
    CREATE OR REPLACE TRIGGER my_schema.trg_Order
    BEFORE INSERT OR UPDATE
    ON my_schema.ORDER
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    BEGIN
    :NEW.LAST_UPDATE_DATE := SYSDATE;
    END;
    If I update the record using PL/SQL with SELECT-FOR-UPDATE & then UPDATE, the column LAST_UPDATE_DATE is not updated with the SYSDATE.
    But if it is done by using the UPDATE Statement, then the column LAST_UPDATE_DATE is correctly updated with the SYSDATE.
    Why? How can I ensure that for SELECT-FOR-UPDATE & then UPDATE will also update the LAST_UPDATE_DATE with SYSDATE.

    The Table Order has a BLOB column.

  • IPhone 4s updated with IOS 8. Not the calendar will not show a full list of dates. Instead it shows the whole month with the list of the day selected. I want to have my full list back. So much easier to scroll thru when making appointments.

    iPhone 4s just updated with IOS 8. Now my calendar does not offer the full list of items by day on the screen. Instead I see the month and below the month are the appointments in a list for the selected day only. I would like the option to have the full list available as it is much easier to scroll thru the list when making appointments.

    Hello memormor,
    Thank you for visiting Apple Support Communities.
    To see the full scrollable list of events, start from the day view (tap on a day), not the month view, then click .
    Calendar at a glance - iPhone
    View a list of events. In month view, tap to see a day’s events. In day view, tap .
    Take care,
    Nubz

  • ITunes 10.5 will not sync to my BlackBerry. I sync's outlook fine with desk top manager, but when I select music DM says connect device. It also tells me to install iTunes!?!? Running XP Pro w/SR3 and BBerry Tourch 9810.

    iTunes 10.5 will not sync to my BlackBerry. I sync's outlook fine with desk top manager, but when I select music DM says connect device. It also tells me to install iTunes!?!? Running XP Pro w/SR3 and BBerry Tourch 9810.

    LowerFilters: AFS2K (3.1.21.0), PXHELP20 (2.0.0.0), IVIASPI (1.0.0.0), CDR4_XP (8.0.0.212),
    UpperFilters: Cdralw2k (8.0.0.212), GEARAspiWDM (2.0.6.1),
    hmmmm. you've got rather a lot of burning software entries in there. (it looks like you've got some kind of Roxio product installed, as well as itunes and Alcohol 120%.)
    by way of experiment, try the technique described in the following document (remember to take a backup of your device filter registry keys first).
    iTunes for Windows: Troubleshooting CD issues caused by device filters
    do you still get the itunes message with just the iTunes filters in place?

  • Batch updates with callable/prepared statement?

    The document http://edocs.bea.com/wls/docs70/oracle/advanced.html#1158797 states
    that "Using Batch updates with the callableStatement or preparedStatement is
    not supported". What does that actually mean? We have used both callable and prepared
    statements with the batch update in our current project (with the Oracle 817 db).
    It seems to run ok anyway.

    So the documentation should state that batch updates do not work ok in old versions
    of JDriver for Oracle, BUT work correctly with newer version. Additionally, batch
    updates work ok when used with Oracle supplied jdbc-drivers?
    "Stephen Felts" <[email protected]> wrote:
    Support for addBatch and executeBatch in the WLS Jdriver for Oracle was
    added in 7.0SP2.
    It was not available in 6.X or 7.0 or 7.0SP1.
    "Janne" <[email protected]> wrote in message news:3edb0cdc$[email protected]..
    The document http://edocs.bea.com/wls/docs70/oracle/advanced.html#1158797
    states
    that "Using Batch updates with the callableStatement or preparedStatementis
    not supported". What does that actually mean? We have used both callableand prepared
    statements with the batch update in our current project (with the Oracle817 db).
    It seems to run ok anyway.

  • Issue with Select options in select statement - ABAP Question

    Hi
    I am facing an issue with select options. Select statement is returning sy-subrc as 4.
    I wrote the program as below:
    SELECT-OPTIONS:
    s_kunnr FOR bsad-kunnr,
    s_lifnr FOR bsak-lifnr,
    s_gjahr FOR bsad-gjahr,
    s_bukrs FOR bsad-bukrs,
    s_saknr FOR bsad-saknr,
    s_budat FOR bsak-budat.
    In start of selection I have written the select statement as
    SELECT * FROM bsak INTO TABLE lt_bsak
    WHERE bukrs IN s_bukrs AND lifnr = s_lifnr AND gjahr IN s_gjahr AND budat IN s_budat AND saknr IN s_saknr.
    In selection screen I have not entered any values and executed the program. I am not getting any result. When I debug that, sy-subrc is 4 at above select statement. But table has records.
    If am removing the "lifnr = s_lifnr " condition in select then select is returning values.
    I am not getting where I made the mistake. Please suggest.
    Thank you
    Hanu

    Hi,
    The problem here with where condition select option lifnr = s_lifnr.
    Use below select query.
    SELECT * FROM bsak INTO TABLE lt_bsak
    WHERE bukrs IN s_bukrs
        AND lifnr     IN s_lifnr
        AND gjahr   IN s_gjahr
        AND budat  IN s_budat
        AND saknr  IN s_saknr.
    s_lifnr is a select option and you are passing it as parameter lifnr = s_lifnr.
    if you want to pass this s_lifnr as single vale then pass in below mentioned way.
    lifnr = s_lifnr-low
    BR,
    Vijay

Maybe you are looking for

  • Unable to Access Remote LAN over IPSec VPN

    I have a Cisco ASA 5540 setup with Remote Access VPN for users. Suddenly no one can access the remote LAN over VPN. Below is my config: ASA Version 7.0(8) hostname DC2ASA domain-name yorktel.com enable password d2XdVlFOzleWlH1j encrypted passwd 2KFQn

  • Adding custom fields to FPE1/2/3 transaction screen

    Hi guys, I need to add custom fields from table DFKKOP to transactions FPE1/2/3 under ADDITIONAL DATA area while manually entering NEW BUSINESS PARTNER ITEM. The transaction is not BDT enabled and does not have a screen exit. The user exit and BaDI d

  • Move out of table using keyboard

    When editing the contents of a table in Design view, is it possible to move the insertion point out of the table using only the keyboard--that is, without having to click the mouse somewhere outside the table.

  • Time Capsule: A very frustrating product.

    Since purchasing my TC I have twice had to erase it and start anew because it was no longer able to backup. Now, I've been getting the following error message over the past couple of days: "Time Machine Error Unable to complete backup. A network prob

  • Web archives and static content

    Most (at least all that I have seen) of the documentation and discussions surrounding Web Archives seem to assume that the web applications static content (images, ..etc) will always reside within the WAR. If your application contains a large amount