我必须更新我的一个错误更新的SQL Server表的数据,这导致一行单元格的数据覆盖了下一行。以下是表应该处于正确状态的示例:
FirstName LastName EmailID
--------------------------------------------------
abc xyz abc.xyz@something.com
def 321 def.321@something.com
ghi 123 ghi.123@something.com
错误的数据已成为:
FirstName LastName EmailID
---------------------------------------------
abc xyz something
def 321 abc.xyz@something.com
ghi 123 def.321@something.com
我知道最后一条记录将无法找到,但至少其他记录应该正确恢复
答案 0 :(得分:1)
假设您的表按firstName排序,lastName可以使用:
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
如果您的数据的排序方式不同,请修改ORDER BY
中的contactCTE
部分以反映此