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

前端 未结 11 1069
旧巷少年郎
旧巷少年郎 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:50

    Try this :

    SELECT CONVERT(varchar(2), GETDATE(), 101)
    
    0 讨论(0)
  • 2020-12-08 06:50

    SQL Server 2012+ (for both month and day):

    SELECT FORMAT(GetDate(),'MMdd')
    

    If you decide you want the year too, use:

    SELECT FORMAT(GetDate(),'yyyyMMdd')
    
    0 讨论(0)
  • 2020-12-08 06:53

    Roll your own method

    This is a generic approach for left padding anything. The concept is to use REPLICATE to create a version which is nothing but the padded value. Then concatenate it with the actual value, using a isnull/coalesce call if the data is NULLable. You now have a string that is double the target size to exactly the target length or somewhere in between. Now simply sheer off the N right-most characters and you have a left padded string.

    SELECT RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DAY, '2012-12-09') AS varchar(2)), 2) AS leftpadded_day
    

    Go native

    The CONVERT function offers various methods for obtaining pre-formatted dates. Format 103 specifies dd which means leading zero preserved so all that one needs to do is slice out the first 2 characters.

    SELECT CONVERT(char(2), CAST('2012-12-09' AS datetime), 103) AS convert_day
    
    0 讨论(0)
  • 2020-12-08 06:57

    Use SQL Server's date styles to pre-format your date values.

    SELECT
        CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero  -- Date Style 101 = mm/dd/yyyy
        ,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero   -- Date Style 103 = dd/mm/yyyy
    
    0 讨论(0)
  • 2020-12-08 06:58
    Select Replicate('0',2 - DataLength(Convert(VarChar(2),DatePart(DAY, GetDate()))) + Convert(VarChar(2),DatePart(DAY, GetDate())
    

    Far neater, he says after removing tongue from cheek.

    Usually when you have to start doing this sort of thing in SQL, you need switch from can I, to should I.

    0 讨论(0)
提交回复
热议问题