How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

前端 未结 11 1068
旧巷少年郎
旧巷少年郎 2020-12-08 06:03
DECLARE @day CHAR(2)

SET @day = DATEPART(DAY, GETDATE())

PRINT @day

If today was the 9th of December, the above would print \"9\".

I want

相关标签:
11条回答
  • 2020-12-08 06:33

    For SQL Server 2012 and up , with leading zeroes:

     SELECT FORMAT(GETDATE(),'MM') 
    

    without:

    SELECT    MONTH(GETDATE())
    
    0 讨论(0)
  • 2020-12-08 06:37
    SELECT RIGHT('0' 
                 + CONVERT(VARCHAR(2), Month( column_name )), 2) 
    FROM   table 
    
    0 讨论(0)
  • 2020-12-08 06:39

    select right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ + right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ + right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

    0 讨论(0)
  • 2020-12-08 06:44

    Pad it with 00 and take the right 2:

    DECLARE @day CHAR(2)
    
    SET @day = RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)
    
    print @day
    
    0 讨论(0)
  • 2020-12-08 06:45
    DECLARE @day CHAR(2)
    
    SET @day = right('0'+ cast(day(getdate())as nvarchar(2)),2)
    
    print @day
    
    0 讨论(0)
  • 2020-12-08 06:46

    Leading 0 day

    SELECT FORMAT(GetDate(), 'dd')
    
    0 讨论(0)
提交回复
热议问题