Update only time from my Datetime field in sql

前端 未结 8 1655
旧时难觅i
旧时难觅i 2020-12-08 14:41

I have a date 2013-12-14 05:00:00.000 in my table.

Now i want to update only time of that date. E.G to 2013-12-14 04:00:00.000

Is there any query to update o

相关标签:
8条回答
  • 2020-12-08 14:50

    use this script:

    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
    
    0 讨论(0)
  • 2020-12-08 14:51

    The previous query update only the hour portion but this query will update all portions of the time i.e hour, minutes, seconds:

    UPDATE TABLE_NAME
    SET DATETIME_FIELD = CONCAT(CAST(DATETIME_FIELD AS Date), ' ', CAST('2016-02-01 09:20:00.0000000' AS TIME))
    
    0 讨论(0)
  • 2020-12-08 14:52

    User the below one to update the Time only for datetime column -

    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       
    
    0 讨论(0)
  • 2020-12-08 15:03

    In case of just updating a particular part of the datetime you can use SMALLDATETIMEFROMPARTS like:

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

    In other cases it may be required to copy parts of datetime to other or update only certain parts of the datetime:

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

    Refer SQL Server Date/Time related API references for more such functions

    0 讨论(0)
  • 2020-12-08 15:07
    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-03-10 09:30:00.000

    0 讨论(0)
  • 2020-12-08 15:09
    UPDATE TABLE_NAME SET DATETIME_FIELD = CAST(CAST(CONVERT(DATE, DATETIME_FIELD,101) AS VARCHAR) + ' 2' + ':' +  '22' AS DATETIME) WHERE (OUR_CONDTTION)
    
    0 讨论(0)
提交回复
热议问题