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

前端 未结 7 1574
孤街浪徒
孤街浪徒 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 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
    

提交回复
热议问题