I'm looking to update existing DATETIME
values to yesterdays date and previous depending on their DATE
order but keep the TIME
part as it is.
For example assuming today's date is 2013-05-15 14:19:50
, and I have two existing DATETIME
values of 2013-01-04 01:25:45
and 2013-01-03 01:08:33
. I would like to programatically update them to 2013-05-14 01:25:45
and 2013-05-13 01:08:33
.
Has anyone got a better way of doing this?
My attempt
IF EXISTS
(
SELECT 1
FROM tempdb..sysobjects
WHERE id = object_id ('tempdb..#Date')
AND xtype = 'U'
)
DROP TABLE #Date
CREATE
TABLE #Date
(
ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED(ID),
[DateTime] DATETIME
)
INSERT
INTO #Date
(
[DateTime]
)
VALUES ('2012-12-31 01:25:45')
,('2012-12-31 01:25:44')
,('2012-12-31 01:25:44')
,('2012-12-30 01:08:34')
,('2012-12-30 01:08:33')
,('2012-12-30 01:08:33')
,('2012-12-29 00:43:01')
,('2012-12-29 00:43:00')
,('2012-12-29 00:43:00')
,('2012-12-28 00:25:07')
,('2012-12-28 00:25:07')
,('2012-12-28 00:25:07')
SELECT *
FROM #Date
;WITH CTE
AS (
SELECT DENSE_RANK() OVER (ORDER BY CONVERT(DATE,[DateTime]) DESC) AS DENSERANK,
[DateTime]
FROM #Date
)
UPDATE CTE
SET [DateTime] = DATEADD(DAY,DATEDIFF(DAY,[DateTime],GETDATE()-DENSERANK),[DateTime])
SELECT *
FROM #Date