How to add datetime field with a time field

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 11:41:13

问题


I have to add time value to existing datetime value using T-SQL in SQL Server 2012.

I was thinking that DATEADD function it might be a solution, but it is not...

Perhaps I have somehow time convert to datetime?

So I have

StartDate 2013-02-18 18:34:40.330 (datetime)

Interval 00:11:00.0000000 (time)

EndDate ? tsql ? (datetime)

Any clue?


回答1:


Try something like this. Note: I am not taking milliseconds here

declare @dt datetime = getdate()
declare @t time = '01:35:45'

select dateadd(second, 
                  datepart(hour,@t) * 3600 + 
                  datepart(minute,@t) * 60 + 
                  datepart(second,@t),
                  @dt)



回答2:


DECLARE @d DATETIME = '2013-02-18T18:34:40.330',
        @t TIME(7)  = '00:11:00.0000000';

SELECT EndDate = DATEADD(SECOND, DATEDIFF(SECOND, 0, @t), @d);

Result:

EndDate
-----------------------
2013-02-18 18:45:40.330

Now, you really shouldn't be storing interval in a time column. time is meant to represent a point in time, not a duration. What happens when the interval is >= 24 hours? You should store the start time and end time of an event (those things are typically at least as relevant as the duration), and you can always calculate the duration from those points.




回答3:


I have been using Azure-DB lately and tried the code below there. This does not work in SQL 2012. See this post for more info on SQL-date arithmetics: Difference in datetime and time arithmetic in Azure-DB vs. sql-server 2008R2

I'm a bit late to the party but since the obvious way to do it is missing...

DECLARE @StartDate datetime
DECLARE @Interval time
DECLARE @EndDate datetime
SET @StartDate = '2013-02-18 18:34:40.330'
SET @Interval = '00:11:00.000000'

SET @EndDate = @StartDate + @Interval

SELECT @StartDate StartDate, @Interval Interval, @EndDate EndDate

Output:
StartDate                  Interval             EndDate
2013-02-18 18:34:40.330    00:11:00.0000000    2013-02-18 18:45:40.330


来源:https://stackoverflow.com/questions/15228132/how-to-add-datetime-field-with-a-time-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!