如何从 SQL Server 中的日期获取月份编号(不是月份名称)?

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

How can I get the month number (not month name) from a date in SQL Server?

sqlsql-serversql-server-2008

提问by mjyazdani

How can I get the month number in sql? I use the following code but it returns the month name.

如何在sql中获取月份数?我使用以下代码,但它返回月份名称。

SELECT DATENAME(mm, GETDATE())

回答by mr_eclair

Use datepart function with m extension.

使用带有 m 扩展名的 datepart 函数。

SELECT DATEPART(m, getdate())

回答by Paul J

Use the month function - SELECT MONTH(GETDATE())

使用月份功能 - SELECT MONTH(GETDATE())

回答by CloudyMarble

Use Datepart:

使用日期部分

DATEPART(mm,getdate());

回答by Daniel Kelley

You want DATEPART:

你想要DATEPART

select datepart(mm, getdate())

回答by Massimiliano Peluso

Try the below:

试试下面的:

SELECT DATEPART(mm,getdate())

回答by ExplodingPony

You can also use this to pad the month number

您也可以使用它来填充月份数字

SELECT RIGHT('00' + RTRIM( CAST( DATEPART( MONTH, GETDATE() ) AS varchar(2)) ) , 2)

回答by Sunil

This will return with two char in case of Jan-Sep:

在 Jan-Sep 的情况下,这将返回两个字符:

SELECT CASE WHEN LEN(MONTH(GETDATE())) = 1 THEN '0' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) 
WHEN LEN(MONTH(GETDATE())) = 2 THEN CAST(MONTH(GETDATE()) AS VARCHAR(2)) END