将DATETIME值更新为< = GETDATE() - 1

时间:2013-05-15 13:25:04

标签: sql-server-2008 tsql sql-server-2005 sql-server-2008-r2

我希望将现有的DATETIME值更新为昨天和之前的日期,具体取决于他们的DATE订单,但保持TIME部分不变。

例如,假设今天的日期为2013-05-15 14:19:50,并且我有DATETIME2013-01-04 01:25:45两个现有的2013-01-03 01:08:33值。我想以编程方式将其更新为2013-05-14 01:25:452013-05-13 01:08:33

有没有人有更好的方法呢?

我的尝试

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

1 个答案:

答案 0 :(得分:0)

我认为这可以取代您当前的UPDATE。是否更好是值得商榷的:

update #Date set DateTime =
     DATEADD(day,
        (select MIN(DATEDIFF(day,DateTime,CURRENT_TIMESTAMP)) from #Date) --How many days since the most recent event recorded?
        -1, --Make that most recent event yesterday
     DateTime)

简单的观察是,每个事件的添加天数是一个常数 - 它只是从最近的事件到今天的天数。