Zack Zack - 4 months ago 9
SQL Question

SQL convert - 2015-1 format date to 2015-01 format

I have a varchar column with values like below

A
2015-4
2015-12
2015-9


I need the new column to look like

A
2015-04
2015-12
2015-09


Any pointers are highly appreciated.

Answer

How about stuff()?

select (case when len(a) = 6
             then stuff(a, 6, 0, '0')
             else a
        end) as a

Or:

select (case when len(a) = 6
             then replace(a, '-', '-0')
             else a
        end) as a