日期时间的填充表每个增加一秒

时间:2013-11-06 20:11:15

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

我有一个MyDatabase.MyTable.DateCol,有几千行,我想用日期时间来填充。我希望每个日期比前一个日期大1秒。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

样本表

CREATE Table DateTable 
(ID INT IDENTITY(1,1),Name NVARCHAR(300), Data Datetime)
GO

测试数据

INSERT INTO DateTable (Name)
VALUES ('John'),('Mark'),('Phil'),('Simon'),('Sam'),('Pete'),('Josh')
GO

<强>查询

;WITH CTE
AS
(
SELECT *, rn = ROW_NUMBER() OVER (ORDER BY ID ASC)  FROM DateTable
)
UPDATE CTE
SET  Data = DATEADD(SECOND, CTE.rn, GETDATE())

结果集

SELECT * FROM DateTable

ID  Name    Data
1   John    2013-11-06 20:34:59.310
2   Mark    2013-11-06 20:35:00.310
3   Phil    2013-11-06 20:35:01.310
4   Simon   2013-11-06 20:35:02.310
5   Sam     2013-11-06 20:35:03.310
6   Pete    2013-11-06 20:35:04.310
7   Josh    2013-11-06 20:35:05.310

答案 1 :(得分:0)

不太确定您的订购标准,但您可以使用:

MIN(DateCol) OVER()

获取第一个日期,

ROW_NUMBER() OVER(ORDER BY DateCol, ID)

获取要添加的秒数(您的订购标准可能不同)。然后将两者结合起来更新公用表表达式:

WITH CTE AS
(   SELECT  ID,
            DateCol,
            NewDate = DATEADD(SECOND, 
                                MIN(DateCol) OVER(), 
                                ROW_NUMBER() OVER(ORDER BY DateCol, ID))
    FROM    MyDatabase.MyTable
)
UPDATE  CTE
SET     DateCol = NewDate;

如果您的列中没有日期,则只需输入开始日期(GETDATE()下方):

WITH CTE AS
(   SELECT  ID,
            DateCol,
            NewDate = DATEADD(SECOND, 
                                GETDATE(), 
                                ROW_NUMBER() OVER(ORDER BY DateCol, ID))
    FROM    MyDatabase.MyTable
)
UPDATE  CTE
SET     DateCol = NewDate;