I have to update the data of one of my SQL Server table that was mistakenly updated, and this caused data of one row's cell to over-write the next. Following is an example of what the table should have been in correct state:
FirstName LastName EmailID
--------------------------------------------------
abc xyz abc.xyz@something.com
def 321 def.321@something.com
ghi 123 ghi.123@something.com
Mistakenly the data has become:
FirstName LastName EmailID
---------------------------------------------
abc xyz something
def 321 abc.xyz@something.com
ghi 123 def.321@something.com
I know that the last one record will not be found but atleast other should be restored correctly
assuming your table is ordered by firstName, lastName you can use this:
declare @contact as table (firstName varchar(255), lastName varchar(255), emailID varchar(255))
insert into @contact (firstName, lastName, emailID)
values
('abc', 'xyz', 'something')
,('def', '321', 'abc.xyz@something.com')
,('ghi', '123', 'def.321@something.com');
with contactCTE(rowNo, firstName, lastName, emailID)
as
(
select
ROW_NUMBER() OVER (ORDER BY firstName, lastName DESC)
,firstName
,lastName
,emailID
from
@contact
)
update c1
set
emailID = c2.emailID
from
contactCTE c1
inner join contactCTE c2 on c1.rowNo +1 = c2.rowNo;
select * from @contact
If your data is ordered differently just modify the ORDER BY
part in contactCTE
to reflect this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.