Rupesh
Rupesh

Reputation: 55

Convert MonthName-Year to Year-MonthNumber

I have a custom date string in SQL. I need to convert the date into custom format. Below is the example for it.

SQL Input : 'January-2019' (Month Name-Year format)
Output    : '201901'       (Year-Month Number format, Month Number must be two digit)

Upvotes: 1

Views: 103

Answers (2)

Suraj Kumar
Suraj Kumar

Reputation: 5643

You can also try this.

DECLARE @input  AS VARCHAR(20) = 'January-2019'
Select Convert(Varchar(6), Cast(Replace(@input, '-', ' 01 ') as DATE), 112)

Live Demo

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272086

Since you're using SQL 2008 you can use CONVERT(DATE, ...) + CONVERT(VARCHAR, ...):

DECLARE @input  AS VARCHAR(20) = 'January-2019'
SELECT CONVERT(VARCHAR(6), CONVERT(DATE, '01-' + @input), 112)

Note that you need to prepend 01- to the string.

Upvotes: 4

Related Questions