Copy data from one existing row to another existing row in SQL? Copy data from one existing row to another existing row in SQL? sql sql

Copy data from one existing row to another existing row in SQL?


Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.

If this is the case, you'll want to use an UPDATE...FROM statement:

UPDATE MyTableSET    complete = 1,    complete_date = newdata.complete_date,    post_score = newdata.post_scoreFROM    (    SELECT        userID,        complete_date,        post_score    FROM MyTable    WHERE        courseID = 6        AND complete = 1        AND complete_date > '8/1/2008'    ) newdataWHERE    CourseID = 11    AND userID = newdata.userID

See this related SO question for more info


UPDATE c11SET    c11.completed= c6.completed,    c11.complete_date = c6.complete_date,-- rest of columns to be copiedFROM courses c11 inner join courses c6 on    c11.userID = c6.userID     and c11.courseID = 11 and c6.courseID = 6     -- and any other checks

I have always viewed the From clause of an update, like one of a normal select. Actually if you want to check what will be updated before running the update, you can take replace the update parts with a select c11.*. See my comments on the lame duck's answer.


Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2SET t1.your_field = t2.your_fieldWHERE t1.other_field = some_conditionAND t1.another_field = another_conditionAND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.