This is in Teradata.
I am trying to write a case statement that can work if the data comes in the following format:
YYYY-MM-DD ex. 2021-12-17
MM/DD/YYYY ex. 12/17/2021
YYYYMMDD ex. 20211217
Excel Serial ex. 44547 Note: This is an Excel format that counts days from 1899-12-30, so 44547 is 12/17/2021
The case statement below works if the data comes in the formats of YYYYMMDD or Excel Serial, but if the data comes in the formats of YYYY-MM-DD or MM/DD/YYYY it only works if I take out the last 2 when's. Otherwise I receive an error for "Datatype Mismatch in THEN/ELSE expression"
CASE
WHEN POSITION('-' IN SUBSTR(DW_EFF_DT, 5)) <> 0 THEN CAST(DW_EFF_DT AS DATE FORMAT 'YYYY-MM-DD')
WHEN POSITION('/' IN SUBSTR(DW_EFF_DT, 5)) <> 0 THEN CAST(DW_EFF_DT AS DATE FORMAT 'MM/DD/YYYY')
WHEN CHARACTERS(TRIM(DW_EFF_DT))=8 THEN CAST(SUBSTR(DW_EFF_DT,1,4)||'-'||SUBSTR(DW_EFF_DT,5,2)||'-'||SUBSTR(DW_EFF_DT,7,2)) AS DATE FORMAT 'YYYY-MM-DD')
WHEN CHARACTERS(TRIM(DW_EFF_DT))=5 THEN CAST('1899-12-30' AS DATE FORMAT 'YYYY-MM-DD') + DW_EFF_DT
ELSE NULL
END AS DW_EFF_DT
Thank you for any help, it is much appreciated.
Edit: Thanks for the answers. They helped me figure it out. The fix is the last When statement needed to look like this:
WHEN CHARACTERS(TRIM(DW_EFF_DT))=5 THEN (CAST(CAST('1899-12-30' AS DATE FORMAT 'YYYY-MM-DD') + DW_EFF_DT AS DATE FORMAT 'YYYY-MM-DD'))