处理sqlserver数据

操作人员误操作,导致有3W+产品数据改了质量等级,根据修改记录cfbspindlequalitylevelrecord表找到时间段内修改记录

select * from cfbspindlequalitylevelrecord where createdtime between '2018-04-03 09:50:00' and GETDATE() order by spindleid,createdtime;

查询发现有部分产品被修改了多次,如果直接根据该记录连表更新会出现,多次的会被第一条记录更新,所以要想办法取出该时间段内所有产品第一次的更新记录,语句如下:

-获取时间范围内第一条修改记录
select a.* from (select * from CfbSpindleQualityLevelRecords where CreatedTime between '2018-04-03 09:50:00' and GETDATE()) a 
where not exists(select 1 
from CfbSpindleQualityLevelRecords b where b.CfbSpindleId=a.CfbSpindleId and b.CreatedTime<a.CreatedTime and b.CreatedTime between '2018-04-03 09:50:00' and GETDATE()) order by a.CfbSpindleId;

#或者
select * from (select t.*,ROW_NUMBER() over(PARTITION by t.cfbspindleid order by t.createdtime asc) num from CfbSpindleQualityLevelRecords t  where t.CreatedTime between '2018-04-03 09:50:00' and GETDATE()) a where num=1 order by a.CfbSpindleId;
--写入临时表temp_reocrd select a.* into temp_reocrd from (select * from CfbSpindleQualityLevelRecords where CreatedTime between '2018-04-03 09:50:00' and GETDATE()) a where not exists(select 1 from CfbSpindleQualityLevelRecords b where b.CfbSpindleId=a.CfbSpindleId and b.CreatedTime>a.CreatedTime and b.CreatedTime between '2018-04-03 09:50:00' and GETDATE()) order by a.CfbSpindleId;
--更新数据
--update cfbspindles set cfbspindles.QualityLevelId=temp_reocrd.FromQualityLevelId from cfbspindles, temp_reocrd where temp_reocrd.CfbSpindleId=cfbspindles.Id and temp_reocrd.CreatedTime between '2018-04-03 09:50:00' and GETDATE()

--验证
select s.Id, s.CfbSpindleNo,s.MtlLocatorId,r.MtlLocatorId,s.QualityLevelId, r.FromQualityLevelId,r.ToQualityLevelId from cfbspindles s inner join temp_reocrd r on r.CfbSpindleId=s.Id where r.CreatedTime between '2018-04-03 09:50:00' and GETDATE()

--删除临时表
drop table temp_reocrd

 

posted @ 2018-04-03 16:15  lnkDel  阅读(196)  评论(0编辑  收藏  举报