在SQL我的日期时间字段只更新时间(Update only time from my Datetim

2019-08-18 05:28发布

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

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

是否有任何查询,更新从时间字段只有时间?

Answer 1:

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))


Answer 2:

用户下面一个仅更新时间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       


Answer 3:

UPDATE TABLE_NAME SET DATETIME_FIELD = CAST(CAST(CONVERT(DATE, DATETIME_FIELD,101) AS VARCHAR) + ' 2' + ':' +  '22' AS DATETIME) WHERE (OUR_CONDTTION)


Answer 4:

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))

OUTPUT:2017年3月10日09:30:00.000



Answer 5:

在刚刚更新,你可以使用datetime的特定部分的情况下SMALLDATETIMEFROMPARTS这样的:

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

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

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

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



Answer 6:

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));


Answer 7:

前面的查询更新仅小时部分,而且该查询将更新的时间,即小时,分,秒所有部分:

UPDATE TABLE_NAME
SET DATETIME_FIELD = CONCAT(CAST(DATETIME_FIELD AS Date), ' ', CAST('2016-02-01 09:20:00.0000000' AS TIME))


文章来源: Update only time from my Datetime field in sql