Domanda

How do you change the DATEPART format of the month to include the 0 in front of the month?

For instance 5 should be 05.

What I have tried, but none of it works, (only gives me 5)

Createdate = 2008-07-25 13:43:48.000

CONVERT(varchar(2), DATEPART(MONTH,(CreatedDate)))
CONVERT(varchar(2), DATEPART(MM,(CreatedDate)))
È stato utile?

Soluzione

With help from SQL Server Date Formats

You can try

DECLARE @Createdate DATETIME = '2008-07-25 13:43:48.000'
SELECT SUBSTRING(CONVERT(VARCHAR(8), @Createdate, 3), 4, 2)

And here is an example

SQL Fiddle DEMO

Altri suggerimenti

I often use RIGHT as a cheap way to CONVERT.

select RIGHT(100+MONTH(CreatedDate),2)

This is what you need

Createdate = 2008-07-25 13:43:48.000

Replace(str(datepart(mm, CreatedDate), 2),' ','0')

Output: 07

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top