使用 T-SQL 从年月日创建日期 [英] Create a date from day month and year with T-SQL

查看:42
本文介绍了使用 T-SQL 从年月日创建日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包含 12, 1, 2007 等单个部分的日期转换为 SQL Server 2005 中的日期时间.我尝试了以下操作:

I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following:

CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME)

但这会导致错误的日期.将三个日期值转换为正确的日期时间格式的正确方法是什么.

but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.

推荐答案

假设 y, m, d 都是 int,怎么样:

Assuming y, m, d are all int, how about:

CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)

请参阅我的其他答案对于 SQL Server 2012 及更高版本

Please see my other answer for SQL Server 2012 and above

这篇关于使用 T-SQL 从年月日创建日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆