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

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

提交回复
热议问题