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

前端 未结 7 1575
孤街浪徒
孤街浪徒 2021-02-02 08:37

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

SELECT DATENAME(mm, GETDATE())
相关标签:
7条回答
  • 2021-02-02 08:50

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

    0 讨论(0)
  • 2021-02-02 08:58

    Try the below:

    SELECT DATEPART(mm,getdate())
    
    0 讨论(0)
  • 2021-02-02 09:00

    This will return with two char in case of 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
    
    0 讨论(0)
  • 2021-02-02 09:02

    You want DATEPART:

    select datepart(mm, getdate())
    
    0 讨论(0)
  • 2021-02-02 09:02

    You can also use this to pad the month number

    SELECT RIGHT('00' + RTRIM( CAST( DATEPART( MONTH, GETDATE() ) AS varchar(2)) ) , 2)
    
    0 讨论(0)
  • 2021-02-02 09:03

    Use datepart function with m extension.

    SELECT DATEPART(m, getdate())
    
    0 讨论(0)
提交回复
热议问题