Update table with select from another table

Hallo,
I'd like to update table b with codes from a mapping table a.
a has:
town_id, town_code, town_name
b has town_code, town_id, town_population, town_zip_code,...
Table a has all the details - town_id, town_code and town_name and acts as the mapping between town_id and town_code
In table b, town_code is null. I want to update the column b.town_code with town_code from table a where a.town_id = b.town_id.
How will the update query look like?
I tried
UPDATE B SET town_code = (SELECT A.town_code FROM A,B WHERE A.town_id=B.town_id)
and I get the error 'single-row subquery returns more than one row'
Will appreciate your assistance

This is what I did.
First, I created and populated the TOWN_INFO table:
CREATE TABLE "TOWN_INFO"
(     "TOWN_ID" NUMBER,
     "TOWN_CODE" NUMBER,
     "E_MAIL" CHAR(15 BYTE)
Table Created.
insert all
into TOWN_INFO (TOWN_ID, E_MAIL) values (3024,'[email protected]')
into TOWN_INFO (TOWN_ID, E_MAIL) values (3040,'[email protected]')
into TOWN_INFO (TOWN_ID, E_MAIL) values (3052,'[email protected]')
into TOWN_INFO (TOWN_ID, E_MAIL) values (3065,'[email protected]')
into TOWN_INFO (TOWN_ID, E_MAIL) values (3066,'[email protected]')
select * from dual
5 rows created.
The following creates and populates the mapping table:
CREATE TABLE "TOWN_MAPP"
(     "TOWN_CODE" NUMBER,
     "TOWN_ID" VARCHAR2(255 BYTE),
     "TOWN_NAME" CHAR(6 BYTE)
insert all
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3024,'1001','TOWN_1')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3040,'1003','TOWN_3')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3052,'1002','TOWN_2')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3065,'1004','TOWN_4')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3066,'1006','TOWN_6')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3088,'1007','TOWN_7')
into TOWN_MAPP (TOWN_ID,TOWN_CODE, TOWN_NAME) values (3020,'1009','TOWN_9')
select * from dual
7 rows created.
And now the update query:
UPDATE TOWN_INFO
SET TOWN_CODE=(SELECT B.TOWN_CODE FROM TOWN_MAPP B, TOWN_INFO C
WHERE B.TOWN_ID=B.TOWN_ID)
SET TOWN_CODE=(SELECT B.TOWN_CODE FROM TOWN_MAPP B, TOWN_INFO C
ERROR at line 2:
ORA-01427: single-row subquery returns more than one row
Thanx in advance
Edited by: user9954260 on Apr 13, 2010 7:40 AM
Edited by: user9954260 on Apr 13, 2010 7:44 AM

Similar Messages

  • Update Nulls With Value from Another Row

    Good Morning,
    I word for a car manufacturer. I am pulling an excel spreadsheet into SQL 2012.The spreadsheet lists one line for each dealer, each carline. So if there are 6 carlines and 65 dealers there will be 390 lines. when the spreadsheet gets to me it looks like
    this:
    Dealer          
    Carline         District         Data         Data         Data
    East Side Craworld Model1
    1 0
    0
    Model2
    1 0 0
    Model3
    1 0
    0 0
    So the Dealer is only listed once. When I pull this into SQL the blank lines are nulls and I want them to be the Dealer name in there. How can I accomplish this with an update.
    Just one thing more. When I programmed in access, I would loop through a table and set a variaiable =Dealer name and not change the variable until the next not null row and then make that the new variable all the while making nulls=the variable. Is there
    a way to accomplish that here.

    The only issue is this file will eventually be a feed and an ftp agent will grab the feed place it somewhere and and there will be a stored package to import it.
    Can I do an update on a null field with the field from the previous record, or am I dealing witht he ordering thing again. I found this code. Will it work?
    select Date
    , GroupId
    , case
    when Comment is not null then Comment
    else
    select Comment
    from YourTable yt2
    where yt1.GroupId = yt2.GroupId
    and yt2.Comment is not null
    and yt2.Date < yt1.Date
    and not exists
    select *
    from YourTable yt3
    where yt1.GroupId = yt2.GroupId
    and yt2.Comment is not null
    and yt3.Date < yt2.Date and yt2.Date < yt1.Date
    ) end as Comment
    from YourTable yt1

  • Update Query with Results From another Procedure

    I am not sure if you can do this or what the proper format of the command might look like.
    I have a stored procedure which insert records into a database. I want to insert the records which are returned by calling another procedure. This other procedure returns a cursor object to a variable named o_rows. Can this be done using Oracle 8i?
    Insert into MyTable
    MyStoredProcedure(oRows);

    You have a couple of options.
    1) You can turn your stored procedure into a pipelined table function. This would allow you to do something like
    INSERT INTO myTable
      SELECT *
        FROM TABLE( myStoredProcedure() );I don't believe that pipelined table functions were available in 8i, however.
    2) The other option would be to fetch rows from the cursor and insert those into your table. Something like
    LOOP
      FETCH oRows INTO col1, col2, col3, col4, ...
      INSERT INTO myTable( <<column list>> )
        VALUES( col1, col2, col3, col4 );Note that for simplicity I am omitting the declarations of the local variables col1, col2, etc. and the check to see whether the cursor was exhausted.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • UPDATE SQL string substitution from another table

    Hi - I've come across a tricky situation where I would want to update a column in all the relevant rows of a table with values obtained from another table WITHIN the same column update using string concatenation. im not getting any clean way of doing this.
    The goal is to achieve something like this:
    UPDATE table1 set col1 =
    'LANG_ID=(%s),'||
    '_CHALLENGE_RESPONSE_=(%s),'||
    'CRDN_NAM=(%s),'||
    'CLNT_MODE=(%s),'||
    'PTY_ID=(%s),'||
    'CRDN_VAL=(%s),' ||
    'USER_TZ_COD=(%s),' ||
    'GTS_USER_ID=(%s),'||
    'SP_ID=(%s),' ||
    'SP_ALIAS=(%s),' ||
    'ORIG_CLNT_ID=(%s)'
    where table1.col1 is null
    and to substitute the (%s) with data from another table2*. An example is:
    update table1 set col1=
    'LANG_ID=(select LANG_ID from table2* where USER_ID = (select USER_ID from table1))' ||
    '_CHALLENGE_RESPONSE_=((select CHALLENGERESPONSE_ from table2* where USER_id = (select USER_ID from table1)),' ||
    etc for the rest of the values

    I tried this -although the database shows that the affected rows are updated! but querying the table doesn't show the values in the column!
    select col1 from table1 where col1 is null
    shows back the original content (DESPITE it showing me xxx rows updated!)
    UPDATE table1 t1
    SET col1 = (SELECT 'LANG_ID=('||lang_id||')_CHALLENGE_RESPONSE_=('||
    CHALLENGERESPONSE_|| ...*
    FROM table2 t2
    WHERE t1.user_id = t2.user_id)
    WHERE t1.col1 is null;

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • Update Rows with info from other Rows in Same Table.

    I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". So what am I doing wrong here??? How can I update only the rows that where also in last months run???
    Thanks in advance for any help!
    Update OpenIssues OI1
    Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
    (Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
    From OpenIssues OI2
    Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    SQLMe

    Hi,
    Welcome to the forum!
    SQLMe wrote:
    I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". If the aliases c1 and c2 aren't defined anywhere, then you can't use them anywhere.
    The WHERE clause of the UPDATE statement can only reference the table being updated, ot1 in this case.
    So what am I doing wrong here??? How can I update only the rows that where also in last months run???
    Thanks in advance for any help!
    Update OpenIssues OI1
    Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
    (Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
    From OpenIssues OI2
    Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    ------------There's a syntax error in the last line. Either something got lost when you posted the code, or you just don't want the keyword AND. You certainly don't want AND immediately after WHERE.
    In general, if it's not obvious how to do an UPDATE, then UPDATE is the wrong tool: you want MERGE instead.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    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.
    See the forum FAQ {message:id=9360002}

  • Selection from Another schema by default without schema name qualifier.

    Hi
    Oracle10g release 2, LinuxOS
    i want my schema (User_1) to always select,insert, update, delete the objects from another schema (User_2) without passing full schema qualifier every time whenever i don't pass any schema name explicitly.
    i.e. if i pass the following guerry
    select * from table_a;
    the table of user User_2.table_a (User_2.table_a) will be queried by default instead of table (User_1.table_a)
    and the same implementation is also required in Functions , procedures, sequences etc.
    Wishes

    Three relatively easy options
    1) Create private synonyms in User_1's schema for each object in User_2's schema, i.e.
    CREATE SYNONYM table_a
       FOR user_2.table_a2) Create public synonyms for each object in User_2's schema. This will make it possible for all users to query user_2's objects without specifying the schema name
    CREATE PUBLIC SYNONYM table_a
       FOR user_2.table_a3) Change the current schema for the session (potentially in a login trigger)
    ALTER SESSION SET current_schema = USER_2There are other options that are a bit more complicated like using enterprise users with shared schemas. But most people are perfectly happy with one of these three.
    Justin

  • HT5181 iPhoto for iOS: Photos in iphoto's Camera Roll folder are not updated automatically with edits from other programs

    How can I solve the problem în the subject?

    How can I solve the problem în the subject?
    What exactly are you trying to do?
    Have you been editing photos in iPhoto and want to add them to your camera rool or photo stream?
    Then do exactly as the article describes, that you lonked to:
    iPhoto for iOS: Photos in Camera Roll are not updated automatically with edits from iPhoto
    Use iPhoto's Sharing to save a copy of the edited photo to the Caera Roll, or explain on mor e detail, what you want to do.
    Regards
    Léonie

  • HT4356 can i airprint to my airprint printer remotely, with ipad, from another wifi connection or only when i am within my own network?

    can i airprint to my airprint printer remotely, with ipad, from another wifi connection or only when i am within my own network?

    Air print, and the normal hp airprint set up requires that the pad and the printer be on the same wifi net work.  The 'connecting' is done by your router.  That means remote printing wont work with the out of the box stuff.  I think you might find some 3rd party apps that do support remote  printing, but i have not seen any reports from users that found a really good solution.  Print n share reads like it might work, i am sure some users will chime in.

  • Updating a date field witha field from another table

    Hi friends
    I have a table called Customer_Type with following fields
    Customer_type ,Active_date, Inactive_date
    regular,11/01/2011
    daily,11/04/2011
    monthly,11/05/2011/11/11/2011
    Tbale 2:Customer
    Customer_name,Customer_type,Customer_Inactive_date
    John,regular,
    James,monthly,
    Jake,daily,
    Jill,monthly
    What i wnat is to update the Customer_inactive_date with the Incative_date field from Customer_type
    based on their Customer_type... So james and Jill would have their rows updated in this scneario ..How can i achive this in pl/Sql
    Thank you in advance...

    Hi,
    You can look at this code; it's not PL/SQL but a simple MERGE statement:
    CREATE TABLE CUSTOMER_TYPE
      type_code VARCHAR2(10),
      active_date DATE,
      inactive_date DATE
    INSERT INTO customer_type VALUES('REGULAR', TO_DATE('11/01/2011', 'DD/MM/YYYY'), null);
    INSERT INTO customer_type VALUES('DAILY', TO_DATE('11/04/2011', 'DD/MM/YYYY'), null);
    INSERT INTO customer_type VALUES('MONTHLY', TO_DATE('11/05/2011', 'DD/MM/YYYY'), TO_DATE('11/11/2011', 'DD/MM/YYYY'));
    CREATE TABLE CUSTOMERS
      customer_name varchar2(10),
      customer_type varchar2(10),
      customer_inactive_date DATE
    INSERT INTO customers VALUES('John', 'REGULAR', null);
    INSERT INTO customers VALUES('James', 'MONTHLY', null);
    INSERT INTO customers VALUES('Jake', 'DAILY', null);
    INSERT INTO customers VALUES('Jill', 'MONTHLY', null);
    MERGE INTO customers dst
    USING customer_type src
    ON (dst.customer_type = src.type_code)
    WHEN MATCHED THEN
      UPDATE set dst.customer_inactive_date = src.inactive_date;
    SELECT * FROM customers;
    CUSTOMER_NAME CUSTOMER_TYPE CUSTOMER_INACTIVE_DATE   
    John          REGULAR                                
    James         MONTHLY       11-NOV-11                
    Jake          DAILY                                  
    Jill          MONTHLY       11-NOV-11                 If you don't understand it, just let me know...

  • Help with select from USREXTID table

    HI,
    I try to select from table USREXTID and when i try to use do the select like below
    SELECT bname FROM usrextid
       INTO TABLE lt_bname
           WHERE type    = 'DN'
           AND extid     =  temp_extid
           AND status    = 'X'.
    here when i take the exact entry from the table i get sy-subrc = 0.
    Working o.k.
    when i try to use the select for SAML like
    SELECT bname FROM usrextid
       INTO TABLE lt_bname
             WHERE type      = 'SA'
               AND extid     =  temp_extid
               AND status    = 'X'.
    I get sy-subrc = 4.
    I have entry on the table with SA and i copy all the entry from EXTID field and put it on
    temp_extid ,
    What can be the problem ?
    Best Regards
    Nina
    Edited by: Nina C on Jun 15, 2009 10:05 AM

    HI,
    i copy the entry from the table exactly and i put it ,
    The problem here is with SA.
    when i copy entry from table with DN it work fine.
    it's behave strange .
    Best Regards
    Nina

  • Populating table with data from another table with fewer columns

    Hi,
    I have 2 tables:
    Table 1:
    Column 1
    Column 2
    Column 3
    Table 2:
    Column 1
    Column 2
    I want to populate Table 1 with all the data from Table 2, and populate Column 3 of Table 1 with numbers from a sequence. Is there a SQL stmt to do this? If not, what is the best way to do it in PL/SQL?
    Thank you
    Shailan

    CREATE SEQUENCE t1_seq
    START WITH 1
    INCREMENT BY 1
    CACHE 100;
    INSERT INTO t1( col1, col2, col3 )
      SELECT col1, col2, t2_seq.nextval
        FROM t2Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Is there a way to fill a cell with a value based on the selection from another cell?

    For example: If have a drop down menu created for Cell A1 with options (Dog 1, Cat 2, Bird 3). Is there a way to fill cell A2 automatically when I select from the drop down menu.
    So if I selected 'Cat' in A1, cell A2 would automatically input the 2.

    I suggest an extensible method that allows you to add other animals:
    This method adds a small table called "Animal Lookup" that matches names (same as in the pop-up menu) with a value.
    The table on the left uses this table to retrieve the value based on the animal:
    B2=VLOOKUP(A2, Animal Lookup :: A:B, 2, 0)
    select B2 and fill down

  • Setting current row of a view based on row selected from another view.

    Hi,
    We have two Views V1 and V2. Both views are based on the same tables except that V1 is based on multiple tables. In our application we are showing a read only table which is based on V1. The user can select a particular record for edit. But the edit page is based on V2 and as a result the first record always shows up for editing even though the user may have selected another record.
    Is there a way we can pass the primary key of the record selected from V1 to V2 and set that record as the current record.
    We have tried setCurrentRowWithKey, but this did not help.
    Regards
    RHY

    Hello,
    post the PK as an URL parameter within the link you open the edit page. Then read this parameter in your page (the page with this link) action class and send it to an ActionBinding:
    JUCtrlActionBinding action = (JUCtrlActionBinding) bc.findCtrlBinding("nameOfBinding");
    ArrayList arrayList= new ArrayList();
    arrayList.add(0,primaryKey);
    action.setParams(arrayList);
    action.doIt();
    In your AppModule create a method nameOfBinding with primaryKey as in parameter
    public void nameOfBinding (Number primaryKey )
    getV2().setWhereClause("PRIMARY_KEY=:0");
    getV2().setWhereClauseParam(0,primaryKey );
    getV2().executeQuery();
    In the AppModule you have to publish this method in "ClientInterface".
    Create an Action binding for this method in your list jsp.
    Hope this helps
    Britta

  • Performance problem with select from _DIFF view

    Hi,
    we have a versioned table with more then one million records. We use the DBMS_WM.SetDiffVersions procedure and select from DIFF view to get data differences between two workspaces. The problem is that the select from the DIFF view is very slow. I takes more than 15 minutes. Has anybody an idea why it consumes so much time? Is there any way how to improve it?
    Thanks and regards
    Ondrej

    Hi,
    This can be due to any number of things, but is typically caused by an inefficient optimizer plan. Make sure that statistics on the _LT table have been recently analyzed.
    Also the following information would be useful:
    1. What is the relationship of the workspaces that you are trying to compare (parent/child, children of the same parent, etc) ?
    2. How many and of what type dml are being performed in the workspaces ?
    3. What version of Workspace Manager are you using and what is the version of the database ?
    4. What is the time needed to select from the _DIFF view based on the primary key ?
    Regards,
    Ben

Maybe you are looking for