2013-04-23 124 views
0

我在我的表中有一個日期時間列,我想更新它,以便獲取今天的日期,但保持時間部分。來自兩個不同日期的時間和日期

例子:

2011-01-21 01:12... -> 2013-04-23 01:12... 
2012-04-20 19:22... -> 2013-04-23 19:22... 

什麼是做到這一點的最簡單的方法?

關於奧斯卡

回答

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) 
+0

該查詢將返回2013-04-23 01:12:00.000 – Devart 2013-04-23 08:22:42

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 
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 ║ 
╚═════════════════════════╝ 
相關問題