开发者

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

开发者 https://www.devze.com 2023-04-02 07:46 出处:网络
This question already has answers here: How to combi开发者_如何学编程ne date from one field with time from another field - MS SQL Server
This question already has answers here: How to combi开发者_如何学编程ne date from one field with time from another field - MS SQL Server (20 answers) Closed 9 years ago.

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


@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)


Try casting them both to DATETIME first:

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


This should work:

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

精彩评论

暂无评论...
验证码 换一张
取 消