Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi all visitors
I have problem about select docdate from table.it display only 1 or 2 or 3 or 4.
but i want it display 01 or 02 or 03 or 04 like that.
I use datepart(month,docdate) and the result only 1,2,3,4,5..........

How can i display 01 or 02 in sql server?

Thanks
TONY
Posted

You can use as
SQL
select right('0' + rtrim(month(dob)),2) from empbirth where name like '%uma%'
 
Share this answer
 
You can use replace(str(datepart(mm,docdate), 2), ' ', '0') as well.
 
Share this answer
 
Comments
[no name] 7-Feb-12 2:37am    
good one!
aravinth santosh 13-May-15 9:56am    
thank you
You can also be lazy and use
SQL
SELECT SUBSTRING (CAST (dob AS NVARCHAR),6,2)

Works just fine. That's if its a date field. For Datetime it might be abit tasking as you must convert it to a date time first, i.e
SQL
SELECT SUBSTRING (CAST (CAST(dob AS DATE) AS NVARCHAR),6,2)
 
Share this answer
 
v2
Comments
CHill60 25-Sep-15 10:27am    
Apart from the fact the question was answered properly over 3 years ago, this "solution" is just wrong. Casting a datetime as nvarchar produces (e.g.) 'Sep 25 2015 3:26PM' - so your sql produces '5 ' as the answer instead of the '09' that was required.
Dennys Henry 27-Oct-15 3:11am    
Sorry about that. If it's a datetime field, you have to first cast it to a date (which might be a lot of work), it works just fine for me since most of the fields am working on are just date fields and not datetime.

However if you test SELECT SUBSTRING(CAST(CAST(GETDATE() AS DATE)AS NVARCHAR),1,7) you get '2015-09' / '2015-10' etc

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900