简体   繁体   中英

Getting error while trying TO_DATE function for procedure conversion

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM