简体   繁体   中英

How to convert yyyymm to Mon-yyyy?

I have a column YearMonth with the value like (201208). I would like to convert the entire column to Aug-2012 (Mon-Year) format. I did upto this point.

select Convert(varchar(11),Cast(right(yearmonth,2)+'-'+left(yearmonth,4) as varchar (11)),0)
from report.TEST

This code changed 201208 to 08-2012 but then I couldn't change it to Aug-2012. Any suggestions. Thanks

实际上,对于SQL Server 2012,有格式函数:

SELECT FORMAT(CONVERT(DATE,yearmonth+'01'), N'MMM-yyyy', 'en-US') AS YearMonth;

For MS-SQL

DECLARE @d1 INT; SET @d1 = 201208
DECLARE @d2 VARCHAR(6); SET @d2 = 201208


SELECT 'data type'='int'
, 'in'=@d1
, 'out'=CONVERT(VARCHAR(3), CAST(LEFT(@d1,6)+'01' AS DATE), 107) 
  + '-' + LEFT(@d1,4)

SELECT 'data type'='varchar'
, 'in'=@d2
, 'out'=CONVERT(VARCHAR(3), CAST(@d2+'01' AS DATE), 107) 
  + '-' +LEFT(@d2,4)


/* -- OUTPUT
data type   in      out
int         201208  Aug-2012

data type   in      out
varchar     201208  Aug-2012
*/

You can also make use of the DATENAME

SELECT 'data type' = 'int'
, 'in' = @d1
, 'out' = LEFT(DATENAME(month, CAST(LEFT(@d1,6)+'01' AS DATE)), 3) 
  + '-' + LEFT(@d1,4)

SELECT 'data type' = 'varchar'
, 'in' = @d2
, 'out' = LEFT(DATENAME(month, CAST(@d2+'01' AS DATE)), 3)
  + '-' + LEFT(@d2,4)

Or use different STUFF :)

DECLARE @d1 INT; SET @d1 = 201208
DECLARE @d2 VARCHAR(6); SET @d2 = 201208


SELECT 'data type' = 'int'
, 'in' = @d1
, 'out' = STUFF(CONVERT(VARCHAR(20), CAST(LEFT(@d1,6)+'01' AS DATE), 107), 4, 5, '-')

SELECT 'data type' = 'varchar'
, 'in' = @d2
, 'out' = STUFF(CONVERT(VARCHAR(20), CAST(@d2+'01' AS DATE), 107), 4, 5, '-')

You'd have to turn 08-2012 into a valid datetime, but this does the trick.

SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ' ', '-') AS [Mon-YYYY]

Source: http://www.sql-server-helper.com/tips/date-formats.aspx

select Substring(Convert(VarChar(11),Convert(DateTime,SomeMinthYear) + '01',113),4,8) would be one way. eg convert the date to one of the formatted strings with a mon yyyy in the format and then chop it out.

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