Home > Software engineering >  Getting error while trying TO_DATE function for procedure conversion
Getting error while trying TO_DATE function for procedure conversion

Time:08-02

There is a cast function that is being used in a Teradata procedure as

cast(<col_name> AS DATE FORMAT 'MM/DD/YY'

It is giving me output as DATE datatype of format 'MM/DD/YY'. I am trying to use similar function in SNOWFLAKE so that it would give me same output. I tried something like this

TO_CHAR(TO_DATE(<col_name>,'MM/DD/YY')

It is giving me output in that format as well, but whenever I am running the Snowflake procedure, different result is getting inserted in the table. This is because my code is giving me result in varchar datatype while the column is of Date datatype. Any idea on how to do this conversion would be highly appreciated.

CodePudding user response:

Snowflake has TRY_DO_DATE, that supports format:

SELECT col_name, TRY_TO_DATE(col_name, 'MM/DD/YY') AS col_name_casted
FROM tab

CodePudding user response:

It appears your data is already stored as a date column. There is a session parameter you can set for input and output date formats so if you have a standard representation of dates you can use that natively in your processing:

alter session set DATE_INPUT_FORMAT='MM/DD/YY';
alter session set DATE_OUTPUT_FORMAT='MM/DD/YY';

select <col_name> from table; -- Now will show as MM/DD/YY for date columns

If you don't wish to do that, then to format it you need to convert to char, format, and then cast to date:

select to_char(col_name,'MM/DD/YY'); -- converts date to char format
select to_date(to_char(col_name,'MM/DD/YY'),'MM/DD/YY'); -- effectively is a no-op
  • Related