Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add datetime field with a time field

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?

like image 767
Friend Avatar asked Mar 05 '13 15:03

Friend


People also ask

How do you add a date and time field?

Right-click the document tab for the new table and click Design View. In the Field Name column, select the first blank row, and then type a name for the field. Select the adjacent cell in the Data Type column, and then select Date/Time or Date/Time Extended from the list. Save your changes.

How do I add time to a date field in SQL?

SQL Server DATEADD() Function The DATEADD() function adds a time/date interval to a date and then returns the date.


1 Answers

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.

like image 165
Aaron Bertrand Avatar answered Oct 29 '22 07:10

Aaron Bertrand