0

我必须更新一个错误更新的 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

我知道最后一条记录将找不到,但至少应该正确恢复其他记录

4

1 回答 1

1

假设你的表是按名字排序的,你可以使用这个:

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以反映这一点

于 2012-09-28T11:27:07.160 回答