Home > Blockchain >  How to Convert CYYMM to YYYY-MM
How to Convert CYYMM to YYYY-MM

Time:05-24

I have some date columns that are formatted as CYYMM (e.g. 12012). I would like to convert these to a typical data representation in SQL Server.

FYI. C stands for century.

E.g. 12012 should be 2020-12 (for December of 2020)

Another

11210 should be 2012-10 (for October of 2012).

How could I go about accomplishing this efficiently and 1900-safe. For example I have accomplished doing it like :

declare @dte int = 12012;
select '20'   left(substring(cast(@dte as char(5)), 2, 5),2)   '-'   right(@dte,2)

But I would like to know if there is a more native solution that doesn't rely on hard coding the '20'.

CodePudding user response:

Assuming first character would be 1 or 0

declare @dte int = 02012;

Select left((@dte/10000 19),2) stuff(right(@dte,4),3,0,'-')

Results

1920-12
  • Related