我的日期是2013-12-14 05:00:00.000。
现在我想只更新该日期的时间。 E.G到2013-12-14 04:00:00.000
是否有任何查询仅从datetime字段更新时间?
答案 0 :(得分:44)
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))
答案 1 :(得分:7)
使用以下内容仅更新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
答案 2 :(得分:3)
UPDATE TABLE_NAME SET DATETIME_FIELD = CAST(CAST(CONVERT(DATE, DATETIME_FIELD,101) AS VARCHAR) + ' 2' + ':' + '22' AS DATETIME) WHERE (OUR_CONDTTION)
答案 3 :(得分:1)
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
答案 4 :(得分:1)
如果仅更新日期时间的特定部分,则可以使用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 Date/Time related API references
答案 5 :(得分: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));
答案 6 :(得分: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
答案 7 :(得分:-2)
上一个查询仅更新小时部分,但此查询将更新时间的所有部分,即小时,分钟,秒:
UPDATE TABLE_NAME
SET DATETIME_FIELD = CONCAT(CAST(DATETIME_FIELD AS Date), ' ', CAST('2016-02-01 09:20:00.0000000' AS TIME))