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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Cast varchar number into Date Format

Author  Topic 

Johnph
Posting Yak Master

103 Posts

Posted - 2013-07-12 : 14:18:48
I have a column (varchar (50)), It has values from 1-12.

I want to cast them to their appropriate months.

Example: 1 = January
2 = Febuary
3 = March
etc.

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-07-12 : 14:28:08
You can use a case expression like this:
CASE yourVarcharCol
WHEN '1' THEN 'January'
WHEN '2' THEN 'February'
--- etc
END AS MonthName;
Alternatively, if you want to make it hard for a non-SQL person to read and understand, you can do the following:
DATENAME(month,DATEADD(mm,CAST(@yourcol AS INT)-1,0))
Go to Top of Page

Johnph
Posting Yak Master

103 Posts

Posted - 2013-07-12 : 14:42:18
Thanks again Jim, I prefer the 2nd method... makes me look like I know what I'm doing.
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-07-12 : 15:03:39
Of course! I must admit that I myself have used "simplified" queries similar to that to pretend to be a know-it-all and to watch people's jaws drop.
Go to Top of Page
   

- Advertisement -