sybase-asa

Copy database field value from one table to another


I use Sybase ASA7, I have 2 tables in a database.

Both tables contain 2 fields - ID and EventDateTime with 20 records.

ID field = 1 to 20 in both tables.

Table 1 has the EventDateTime field filled in against each ID, table 2 does not, they are just null values.

How would I loop through and copy each eventDateTime field from table 1 to table 2 so the two tables match ?

Not really familiar with SQL, so apologies.


Solution

  • One option:

    update Table2
    set    EventDateTime = Table1.EventDateTime
    from   Table2
    join   Table1
    on     Table2.ID            =  Table1.ID
    and    Table2.EventDateTime is NULL
    

    Another option, based on your comments that the tables are the same structure and have the same data (except for the NULL EventDateTime columns):

    delete Table2
    
    insert into Table2 (ID, EventDateTime) select ID, EventDateTime from Table1
    

    Though if you have any delete/insert triggers and/or RI constraints on Table2, this may not be advisable (depending on trigger logic) or doable (in the case of PK/FK constraints).