将日期和时间字段组合到日期时间,SQL Server 2008

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7289753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:59:08  来源:igfitidea点击:

combining Date and Time fields to DateTime, SQL Server 2008

sqlsql-server-2008

提问by codeputer

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

我真的必须:1) 转换为字符串,然后转换为日期时间字段吗?2)使用 DateAdd 和 DatePart 先添加小时,然后是分钟,然后是秒......

回答by Mikael Eriksson

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

在 SQL Server 2012 中,我假设在 SQL Server 2014 中您需要将日期和时间变量都转换为日期时间。

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

回答by jdavies

Try casting them both to DATETIME first:

首先尝试将它们都投射到 DATETIME:

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

回答by Arun

This should work:

这应该有效:

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