SQL SQL中的日期序列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3355015/
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 06:58:38  来源:igfitidea点击:

Date serial in SQL?

sqlsql-servertsqldate

提问by Stefan Steiger

How can I convert a day [1-31] and a month [1-12] and a year (all int), to a date serial IN SQL (without converting to varchar)?

如何将一天 [1-31] 和一个月 [1-12] 和一年(所有整数)转换为日期序列 IN SQL(不转换为 varchar)?

回答by gbn

Zero is 01 jan 1900 in SQL, so you can use this:

SQL 中的零是 1900 年 1 月 1 日,因此您可以使用以下命令:

DATEADD(day, @dayval-1,
     DATEADD(month, @monthval-1,
         DATEADD(year, @yearval-1900, 0)
     )
)

Edit, Feb 2018

编辑,2018 年 2 月

As the other answer says, since SQL Server 2012 (released after the original answer) we can use DATEFROMPARTS

正如另一个答案所说,由于 SQL Server 2012(在原始答案之后发布)我们可以使用 DATEFROMPARTS

 SELECT DATEFROMPARTS (@yearval, @monthval, @dayval)

回答by jakdep

A few functions have been added in SQL Server 2012 which will allow you to do this with DATEFROMPARTS, DATETIMEFROMPARTSand TIMEFROMPARTSamongst others.

SQL Server 2012 中添加了一些函数,允许您使用DATEFROMPARTSDATETIMEFROMPARTSTIMEFROMPARTS等来执行此操作 。

Example:

例子:

SELECT DATEFROMPARTS(2018,2,1) -- returns 2018-02-01