Question

I have a table on sql server (SSMS) with a column that contains 4-digit codes. Say 0713 stands for July 2013, and 0114 stands for Jan 2014. Now I want to convert the former to the latter, I wonder what can be the most efficient sql query to convert?

Thanks for any advice!

Was it helpful?

Solution

Probably the most efficient way is a case statement:

select (case left(col, 2)
          when '01' then 'January '
          when '02' then 'Feburary '
          . . .
          when '12' then 'December '
        end) + right(col, 2)

This has the fewest calls to functions. There are more concise ways to do this, such as:

select datename(month, cast('2013' + col as datetime)) + right(col, 2)

Of course, to get the most efficient, you should set up a test in your environment on something like 1 million records and actually test the different timings.

For instance, it might be fastest to have a reference table with 366 entries, one for each day, and use a join to do the conversion.

OTHER TIPS

On your final format it looks like you are wavering between values (Jan for January, but the full month name for July, instead of Jul). In that case, a look up table for the formatted months and a query to it.

Your FormattedMonth table could contain MonthName (the string you want to use) and MonthNumber (this would be most efficient as an int)

For Example:

SELECT originaldates.identifier, FormattedMonth.MonthName + ' 20' + originaldates.year
FROM (Select identifier, left(shortdate,2) as month, right(shortdate,2) as year
        from Tablecontainingfield) originaldates
JOIN FormattedMonth 
ON   cast(FormattedMonth.MonthNumber as int) = originaldates.month
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top