Sql Server中Update用法的心得

本文介绍了一种在SqlServer中处理时间戳重复记录的方法,通过将重复的in_date字段值依次增加一秒来实现数据的唯一性。文章提供了从创建测试环境到最终更新数据的完整SQL脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sql Server中Update用法的心得 

问题: 表中有两字段:id_no (varchar)  ,   in_date   (datetime)   ,把in_date   相同的记录的in_date依次累加1秒,

             使in_date没有相同的记录。

如以下原始数据: 
id_no         in_date
5791 2003-9-1   14:42:02
5792 2003-9-1   14:42:02
5794 2003-9-1   14:42:02
5795 2003-9-1   14:42:03
5796 2003-9-1   14:42:03
5797 2003-9-1   14:42:03
5831 2003-9-1   14:42:04
5832 2003-9-1   14:42:14
5833 2003-9-1   14:42:14

得到结果是:

id_no         in_date
5791 2003-9-1   14:42:02
5792 2003-9-1   14:42:03
5794 2003-9-1   14:42:04
5795 2003-9-1   14:42:05
5796 2003-9-1   14:42:06
5797 2003-9-1   14:42:07
5831 2003-9-1   14:42:08
5832 2003-9-1   14:42:14
5833 2003-9-1   14:42:15

处理方法:

 

--建立测试环境
create table a(id_no varchar(8),in_date datetime)
go
insert into a select '5791','2003-9-1 14:42:02'
union all select '5792','2003-9-1 14:42:02'
union all select '5794','2003-9-1 14:42:02'
union all select '5795','2003-9-1 14:42:03'
union all select '5796','2003-9-1 14:42:03'
union all select '5797','2003-9-1 14:42:03'
union all select '5831','2003-9-1 14:42:04'
union all select '5832','2003-9-1 14:42:04'
union all select '5833','2003-9-1 14:42:04' 
union all select '5734','2003-9-1 14:42:02'
union all select '6792','2003-9-1 14:42:22'
union all select '6794','2003-9-1 14:42:22'
union all select '6795','2003-9-1 14:42:23'
union all select '6796','2003-9-1 14:42:23'
union all select '6797','2003-9-1 14:42:23'
union all select '6831','2003-9-1 14:42:34'
union all select '6832','2003-9-1 14:42:34'
union all select '6833','2003-9-1 14:42:54' 
union all select '6734','2003-9-1 14:42:22'
go
--生成临时表,按照in_date排序
select * into # from a order by in_date
--相同的时间,加一秒。加完了不带重复的
declare @date1 datetime,@date2 datetime,@date datetime
update # 
  
set @date=case when @date1=in_date or @date2>=in_date then dateadd(s,1,@date2else in_date end,
      
@date1=in_date,
      
@date2=@date,
      in_date
=@date
--更新到基本表中去
update a set a.in_date=b.in_date from a a join # b on a.id_no=b.id_no

select * from a
drop table #,a

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值