我的表格中有一个日期时间列,我想更新它,以便它可以获得今天的日期,但保留时间部分。
示例:
2011-01-21 01:12... -> 2013-04-23 01:12...
2012-04-20 19:22... -> 2013-04-23 19:22...
最简单的方法是什么?
关于奥斯卡
答案 0 :(得分:1)
试试这个 -
DECLARE @date_old DATETIME
SELECT @date_old = '2011-01-21 01:12'
DECLARE @date_new DATETIME
SELECT @date_new = '2013-04-23 05:24'
SELECT CAST(CAST(@date_new AS DATE) AS DATETIME) + CAST(@date_old AS TIME)
答案 1 :(得分:1)
修改以下是经过测试的解决方案
DECLARE @Today DATETIME2(7)
Declare @OldDate DateTime2(7)
SET @Today=GETDATE()
Select @OldDate = date From <SomeDatabase>
SELECT DATEADD(day, -DATEDIFF(day, @Today, @OldDate), @OldDate)
这是更新:
Update <SomeDatabase> Set date = DATEADD(day, -DATEDIFF(day, @Today, @OldDate), @OldDate) where date = @OldDate
答案 2 :(得分:0)
要更新表,请使用self join
并使用@Devart的方法保留time
,但更新date
值
Declare @Sample table ( myDate datetime )
Insert into @Sample
values
('2013-04-21 11:42:51.897'),('2013-04-22 13:42:51.897')
Select * from @Sample
Update t
set myDate =convert(datetime,convert(date,getdate())) + convert (time,s.mydate)
from @Sample t inner join @Sample s
on s.myDate=t.myDate
Select * from @Sample
初步结果
╔═════════════════════════╗
║ myDate ║
╠═════════════════════════╣
║ 2013-04-21 11:42:51.897 ║
║ 2013-04-22 13:42:51.897 ║
╚═════════════════════════╝
最终结果
╔═════════════════════════╗
║ myDate ║
╠═════════════════════════╣
║ 2013-04-23 11:42:51.897 ║
║ 2013-04-23 13:42:51.897 ║
╚═════════════════════════╝