Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining Date and Time fields to DateTime, SQL Server 2008 [duplicate]

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.....

like image 647
codeputer Avatar asked Sep 02 '11 22:09

codeputer


People also ask

How do I concatenate two date columns in SQL?

To combine date and time column into a timestamp, you can use cast() function with concat(). select cast(concat(yourDateColumnName, ' ', yourTimeColumnName) as datetime) as anyVariableName from yourTableName; In the above concept, you will use cast() when your date and time is in string format.

Can you convert date to datetime in SQL?

We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.

Can we extract date from timestamp in SQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)


1 Answers

@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) 
like image 143
Mikael Eriksson Avatar answered Oct 02 '22 18:10

Mikael Eriksson