Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
How?I have a query that extracts the month number and year and then uses a CAST statement to join the two (concatenate them if you're familiar with Excel).How do I add a leading zero to months January (1) thru September (9) to make them two digits (01 and 09 in this example).Thanks in advance.
SELECT MONTH (ORDER_DATE) AS MONTH_NO ,YEAR (ORDER_DATE) AS YEAR_ID ,CAST (YEAR(ORDER_DATE) AS VARCHAR(4)) + CAST(MONTH(ORDER_DATE) AS VARCHAR(2)) AS ID
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-03-01 : 07:49:06
You can use this:
CAST (YEAR(ORDER_DATE) AS VARCHAR(4)) + RIGHT('0'+CAST(MONTH(ORDER_DATE) AS VARCHAR(2)),2) AS ID,
But, I prefer to use one of the following - more compact and fewer conversions