0

I would like to convert one of my date column to just month

I have columns values as

example :

select datecolumn from abc 

datecolumn

jan-20 feb-20 mar-20 apr-20 

I would like to get only month in the form

01 02 03 04 
4
  • Please check datepart Commented Feb 20, 2020 at 22:41
  • Is that column of a date-like datatype, or it's a string? Commented Feb 20, 2020 at 22:42
  • That isnt a date, that's clearly a varchar. You should really fix the data type, them you can use things like DATEPART. Commented Feb 20, 2020 at 22:48
  • 20 years after Y2K and people are STILL making this basic mistake! Commented Feb 20, 2020 at 23:09

4 Answers 4

1

I would use either MONTH or DATEPART functions

SELECT DATEPART(month, '2014/04/28'); 

Result: 4

Sign up to request clarification or add additional context in comments.

Comments

0

The data types are not correct. But you can create a new column with the format you want:

alter table t add datecol_mmmyy as (left(datename(month, datecol), 3) +'-' + datename(year, datecol)); 

Then you can refer to datecol_mmmyy and get the format you want.

Comments

0

Untested and quite sketchy but this could work:

select case when datecolumn like 'Jan%' then '01' when datecolumn like 'Feb%' then '02' when datecolumn like 'Mar%' then '03' when datecolumn like 'Apr%' then '04' when datecolumn like 'May%' then '05' when datecolumn like 'Jun%' then '06' when datecolumn like 'Jul%' then '07' when datecolumn like 'Aug%' then '08' when datecolumn like 'Sep%' then '09' when datecolumn like 'Oct%' then '10' when datecolumn like 'Nov%' then '11' when datecolumn like 'Dec%' then '12' end as datecolumn from abc 

Comments

0

You can add a '01-' to the beginning of the field and then use DATEPART function:

DECLARE @Month char(10) = 'Feb-20' select DATEPART(MM,'01-'+@Month) 

If you want the output in two characters, then you can use the format funtion:

DECLARE @Month char(10) = 'Feb-20' select FORMAT(DATEPART(MM,'01-'+@Month),'00') 

Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.