combining Date and Time fields to DateTime, SQL Server 2008

SqlSql Server-2008

Sql Problem Overview


Ok - I've asked a few people and there has got to be an easy way to do this....

declare @Date date
declare @Time time 
declare @datetime datetime

select @Date = convert(Date,GetDate()) 
select @Time = convert(Time,GetDate())

select @Date, @Time, @Date + @Time (+ operator fails!)

Do I really have to:

  1. convert to a string, then convert to datetime field?
  2. use DateAdd and DatePart to add hours first then minutes, then seconds.....

Sql Solutions


Solution 1 - Sql

@Date + cast(@Time as datetime)

In SQL Server 2012 and I assume SQL Server 2014 you neeed to cast both the date and the time variable to datetime.

cast(@Date as datetime) + cast(@Time as datetime)

Solution 2 - Sql

Try casting them both to DATETIME first:

SELECT CAST(@Date AS DATETIME) + CAST(@Time AS DATETIME)

Solution 3 - Sql

This should work:

select @Date, @Time, CAST(@Date AS datetime) + CAST(@Time AS datetime)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodeputerView Question on Stackoverflow
Solution 1 - SqlMikael ErikssonView Answer on Stackoverflow
Solution 2 - SqljdaviesView Answer on Stackoverflow
Solution 3 - SqlArunView Answer on Stackoverflow