简体   繁体   中英

Convert date of format dd mon yyyy to return integer of month in SQL

I have a varchar variable containing value 01 May 2013 and I need to obtain the integer of the Month part.

for eg if 01 May 2013 is input I should get the result as 5

The query I wrote was :

select DATEPART(MM,CONVERT(DATETIME,CONVERT(VARCHAR(15),'01 '+SUBSTRING(FISCAL_MONTH,1,3)+' 2013'),100))
FROM <table name>

Here FISCAL_MONTH is my column name from the table. However this query is showing me the result, for eg 11 for November but is also throwing the following error : Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.

I have tried various combinations, bit in vain. Kindly note I need it in a query. Kindly help.

如果那是您要转换的唯一日期,则可以将SQL语句简化为:

select datepart(mm,convert(datetime,'01 May 2013'))

I just used this to test and it worked:

declare @t as varchar(333)
set @t = '01 May 2013'

select datepart(mm,convert(datetime, @t))

Gives me

5

If you are still getting that conversion error, then you either have some NULL values OR some date values that are not in the correct format . Check the data in your table to see which it is.

I'll leave it to you to add the rest of the months.

select case substring('01 MAY 2013',4,3) when 'JAN' then 1 
when 'FEB' then 2
when 'MAR' then 3    
when 'APR' then 4
when 'MAY' then 5 
when 'JUN' then 6 else 9999 end

It might just be that there is a 3 instead of a 2 in the substring argument:

SUBSTRING(FISCAL_MONTH,1, 2 )+' 2013'),100))

The concat might work also: select DATEPART(MM, CONCAT('01/', substring(convert(varchar(15),'03/23/2013'),1,2),'/2013'));

Wow, it is real interesting to see all the weird code that people come up with. I use the KISS policy most of the time (keep it simple stupid).

How about the MONTH() function. It has been in the TSQL language forever. I even threw in a coalesce to handle any unexpected NULLS.

-- Simple date as text
declare @var_test varchar(20) = '01 may 2013';

-- Use coalesce to handle nulls, use month to return int
select month(coalesce(@var_test, '01 jan 1900')) as my_month_index

Select month ( cast ( date_col as datetime )) From table

You have to convert with proper format, you have to pass the apprpriate format-style value on your conversion. As per MSDN, you are using "dd mon yy" format, so you have to supply the corresponding format-style-code 6 or 106

Declare @FISCAL_MONTH nvarchar(max) = '01 May 2013'
select datepart(mm,Convert(datetime, @FISCAL_MONTH, 6))
--5

Set @FISCAL_MONTH = '01 November 2013'
select datepart(mm,Convert(datetime, @FISCAL_MONTH, 6))
--11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM