I ran into a problem in my job where I mistakenly updated a whole bunch of records. So to revert it back, I followed this question, ordered all the records of the table according to descending order of date of modification, got the second last record, which gave me the value that was prior to my mistaken update. So I wrote something like this to update the record:
update table1 set col1 = (select top 1 col1 from
(select top 2 * from table1 where col2 = val1 order by dateofmodification desc) X
order by dateofmodification
where col2 = val1
It works well but here's the problem. I have a whole bunch of records to update, i.e., a whole lot of values to which col2
matches, i.e., val1, val2, val3, .....
. I can't put in a range of values because of the two WHERE
clauses like so :
update table1 set col1 = (select top 1 col1 from
(select top 2 * from table1 where col2 in (val1, val2, val3) order by dateofmodification desc) X
order by dateofmodification
where col2 in (val1,val2, val3)
because how would SQL server know val1 is to be matched to val1 in the two WHERE
clauses?
Can anyone help me what to do here?
Edit: Here's a sample table
Employees
name | emp_id | address | department | dateofmodification
I made a mistake and update a bunch of employees' records and messed up their department to some random junk.
So if I run this query
update Employees set department = (select top 1 department from
(select top 2 * from Employees where address = 'Chicago' order by dateofmodification desc) X
where address = 'Chicago'
it works well, but there are a whole bunch of cities, not just Chicago. I don't want to plug in those values one by one.