如何在SQL Server中动态更改日期

时间:2012-05-18 06:31:17

标签: sql sql-server

我的程序输出类似于

Jan  1 1900 10:30PM
Jan  1 1900 10:45PM
Jan  1 1900 11:00PM
Jan  1 1900 11:30PM
Jan  1 1900 11:45PM
Jan  2 1900 12:00AM
Jan  2 1900 12:15AM
Jan  2 1900 12:30AM
Jan  2 1900 12:45AM
Jan  2 1900  1:00AM

我想添加当前日期和时间,并在上午12:00之后更改日期

像这样:

Friday,MAY,18 10:30PM
Friday,MAY,18 10:45PM
Friday,MAY,18 11:00PM
Friday,MAY,18 11:30PM
Friday,MAY,18 11:45PM
Friday,MAY,19 12:00AM
Friday,MAY,19 12:15AM
Friday,MAY,19 12:30AM
Friday,MAY,19 12:45AM
Friday,MAY,19  1:00AM

怎么做?

提前致谢

2 个答案:

答案 0 :(得分:1)

从SQL Server 2008:

select YourTimeCol+cast(getdate() as date)
from YourTable

Pre SQL Server 2008:

select YourTimeCol+dateadd(day, datediff(day, 0, getdate()), 0)
from YourTable

SE-Data

答案 1 :(得分:0)

我认为你需要这个

DECLARE @tt TABLE (Sday VARCHAR(50))
INSERT INTO @tt VALUES('Jan 1 1900 10:30PM'),('Jan 1 1900 10:45PM'),('Jan 1 1900 11:00PM'),('Jan 1 1900 11:30PM'),('Jan 1 1900 11:45PM'),('Jan 2 1900 12:00AM'),('Jan 2 1900 12:15AM'),('Jan 2 1900 12:30AM'),('Jan 2 1900 12:45AM'),('Jan 2 1900 1:00AM')

SELECT Sday,DATEADD(DAY,(DATEDIFF(DAY,'1900-01-01',GETDATE())),Sday) AS resultAsDatetime,
CONVERT(VARCHAR(50),DATEADD(DAY,(DATEDIFF(DAY,'1900-01-01',GETDATE())),Sday),109) AS result
FROM @tt

正在返回

Jan 1 1900 10:30PM  2012-05-18 22:30:00.000 May 18 2012 10:30:00:000PM
Jan 1 1900 10:45PM  2012-05-18 22:45:00.000 May 18 2012 10:45:00:000PM
Jan 1 1900 11:00PM  2012-05-18 23:00:00.000 May 18 2012 11:00:00:000PM
Jan 1 1900 11:30PM  2012-05-18 23:30:00.000 May 18 2012 11:30:00:000PM
Jan 1 1900 11:45PM  2012-05-18 23:45:00.000 May 18 2012 11:45:00:000PM
Jan 2 1900 12:00AM  2012-05-19 00:00:00.000 May 19 2012 12:00:00:000AM
Jan 2 1900 12:15AM  2012-05-19 00:15:00.000 May 19 2012 12:15:00:000AM
Jan 2 1900 12:30AM  2012-05-19 00:30:00.000 May 19 2012 12:30:00:000AM
Jan 2 1900 12:45AM  2012-05-19 00:45:00.000 May 19 2012 12:45:00:000AM
Jan 2 1900 1:00AM   2012-05-19 01:00:00.000 May 19 2012  1:00:00:000AM
显然,您可以选择正确的格式将DATETIME转换为VARCHAR,如CONVERT函数中所述,但我认为这不需要帮助。 希望这会有所帮助。