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

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

提交回复
热议问题