SQL 获取本月的 2 位数字

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

Get 2 Digit Number For The Month

sqlsql-serversql-server-2008tsql

提问by Adam

I have an integer column "Month" I would like to get 2 digit number for month.

我有一个整数列“月”,我想获得月份的 2 位数字。

This is what I have tried: DATEPART(mm, @Date)

这是我尝试过的: DATEPART(mm, @Date)

It returns one digit for months January to September I am using SQL Server 2008

它返回一月到九月的一位数我使用的是 SQL Server 2008

Anyone has suggestion?

有人有建议吗?

回答by Ankit Suhail

there are different ways of doing it

有不同的方法来做到这一点

  • Using RTRIMand specifing the range:
  • 使用RTRIM并指定范围

like

喜欢

SELECT RIGHT('0' + RTRIM(MONTH('12-31-2012')), 2); 
  • Using Substringto just extract the month partafter converting the date into text
  • 将日期转换为文本后,使用Substring仅提取月份部分

like

喜欢

SELECT SUBSTRING(CONVERT(nvarchar(6),getdate(), 112),5,2)

see Fiddle

小提琴

There may be other ways to get this.

可能有其他方法可以得到这个。

回答by user3829053

Function

功能

FORMAT(date,'MM') 

will do the job with two digit.

将完成两位数的工作。

回答by SchmitzIT

Pinal Dave has a nice article with some examples on how to add trailing 0s to SQL numbers.

Pinal Dave 有一篇很好的文章,其中有一些关于如何向 SQL 数字添加尾随 0 的示例。

One way is using the RIGHTfunction, which would make the statement something like the following:

一种方法是使用该RIGHT函数,它会使语句类似于以下内容:

SELECT RIGHT('00' + CAST(DATEPART(mm, @date) AS varchar(2)), 2)

回答by Mário Meyrelles

Another simple trick:

另一个简单的技巧:

SELECT CONVERT(char(2), cast('2015-01-01' as datetime), 101) -- month with 2 digits
SELECT CONVERT(char(6), cast('2015-01-01' as datetime), 112) -- year (yyyy) and month (mm)

Outputs:

输出:

01
201501

回答by Vinay Mishra

CONVERT(char(2), getdate(), 101)

转换(字符(2),getdate(),101)

回答by John Woo

Alternative to DATEPART

替代 DATEPART

SELECT LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)

回答by Elias Hossain

Simply can be used:

可以简单地使用:

SELECT RIGHT('0' + CAST(MONTH(@Date) AS NVARCHAR(2)), 2)

回答by Saksham

append 0 before it by checking if the value falls between 1 and 9 by first casting it to varchar

通过首先将值强制转换为 varchar 来检查值是否介于 1 和 9 之间,在它之前附加 0

select case when DATEPART(month, getdate()) between 1 and 9 
then '0' else '' end + cast(DATEPART(month, getdate()) as varchar(2))

回答by TechDo

Try:

尝试:

select right ('0'+convert(nvarchar(2), DATEPART(mm, getdate())),2 )

回答by Angelo Canepa

For me the quickest solution was

对我来说,最快的解决方案是

DATE_FORMAT(CURDATE(),'%m')