我有MyDatabase.MyTable.DateCol
几千行,我想用日期时间填充。我希望每个日期都比前一个日期大 1 秒。我怎样才能做到这一点?
问问题
1564 次
2 回答
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
于 2013-11-06T20:38:38.313 回答
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;
于 2013-11-06T20:37:36.137 回答