33

我的表中有一个日期 2013-12-14 05:00:00.000。

现在我只想更新那个日期的时间。EG 至 2013-12-14 04:00:00.000

是否有任何查询仅从日期时间字段更新时间?

4

9 回答 9

55
UPDATE MyTable 
SET MyDate = DATEADD(HOUR, 4, CAST(CAST(MyDate AS DATE) AS DATETIME)) 

或这个

UPDATE MyTable 
SET MyDate = DATEADD(HOUR, 4, CAST(FLOOR(CAST(MyDate AS FLOAT)) AS DATETIME))
于 2013-03-29T09:26:48.403 回答
9

使用以下内容仅更新datetime列的时间 -

select  CONVERT(varchar(10),datecolumn, 120) + ' 12:34:56', 
        CONVERT(varchar(10),datecolumn, 120) + ' 00:00:00', 
        RSLV_LTR_INITIAL_DUE_DT, *
from twhere able1       
于 2017-05-24T04:49:52.063 回答
3
UPDATE TABLE_NAME SET DATETIME_FIELD = CAST(CAST(CONVERT(DATE, DATETIME_FIELD,101) AS VARCHAR) + ' 2' + ':' +  '22' AS DATETIME) WHERE (OUR_CONDTTION)
于 2013-03-29T09:28:34.413 回答
3
DECLARE @Time as TIME;
DECLARE @Date as DATETIME;

SELECT @Time = CONVERT(TIME, '2016-01-01 09:30:00.000');
SELECT @Date = CONVERT(date, GETDATE()); --2017-03-10 16:37:34.403

SELECT DATEADD(MINUTE, DATEPART(MINUTE, @Time), DATEADD(HH, DATEPART(HOUR, @Time), @Date))

输出: 2017-03-10 09:30:00.000

于 2017-03-10T11:08:25.230 回答
2

如果只是更新日期时间的特定部分,您可以使用SMALLDATETIMEFROMPARTS如下:

UPDATE MyTable 
SET MyDate = SMALLDATETIMEFROMPARTS(YEAR(MyDate), MONTH(MyDate), DAY(MyDate), <HoursValue>, <MinutesValue>) 

在其他情况下,可能需要将部分日期时间复制到其他或仅更新日期时间的某些部分:

UPDATE MyTable 
SET MyDate = SMALLDATETIMEFROMPARTS(YEAR(MyDate), MONTH(MyDate), DAY(MyDate), DATEPART(hour, MyDate), DATEPART(minute, MyDate)) 

有关更多此类功能,请参阅SQL Server 日期/时间相关 API 参考

于 2019-02-13T08:18:27.603 回答
1

使用它来更改字符串的整个时间部分:

UPDATE MyTable SET MyColumn = DATEADD(DAY, DATEDIFF(DAY, 0, MyColumn), '04:00:00')
于 2021-09-01T13:03:22.277 回答
0
DECLARE @d datetime;
SELECT @d = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0);

DECLARE @t time(7);
SET @t = CAST('10:10:10' AS time);

SELECT CONVERT(datetime, CONVERT(varchar(10), CONVERT(date, @d, 101)) + ' ' + CONVERT(varchar(8), @t));
于 2015-10-10T16:04:01.763 回答
0

使用这个脚本:

declare @curDate datetime=getdate() --or any other datetime 
declare @time time='22:31'
declare @hour int ,@min int
set @hour=datepart(hh,@time)
set @min=datepart(mm,@time)
select @curDate=Dateadd(HOUR,@hour,convert(datetime,convert(Date,@curDate)))
select @curDate=Dateadd(MINUTE,@min,@curDate)
Select @curDate
于 2019-07-06T05:26:30.347 回答
-2

上一个查询仅更新小时部分,但此查询将更新时间的所有部分,即小时、分钟、秒:

UPDATE TABLE_NAME
SET DATETIME_FIELD = CONCAT(CAST(DATETIME_FIELD AS Date), ' ', CAST('2016-02-01 09:20:00.0000000' AS TIME))
于 2018-08-30T07:00:39.450 回答