Snowflake日期从varchar转换

huangapple go评论55阅读模式
英文:

Snowflake date conversion from varchar

问题

在我的表中,有一个字段是varchar数据类型。我需要将它转换为YYYYMMDD格式的日期。

我正在尝试使用date、to_date、try_to_date和to_timestamp函数。

SELECT
	START_DATE AS START_DATE_ORIG,
	TRY_TO_DATE(START_DATE, 'YYYYMMDD') AS START_DATE
FROM MY_TABLE;

它们要么报错如下:

SQL Error [100097] [22007]: 无法将 '12/1/2018 12:00:00 AM' 解析为 'YYYYMMDD' 格式的日期

要么显示带有空值的结果,如下图所示:

Snowflake日期从varchar转换

英文:

I have a field in my table that is a varchar datatype. I need to convert it to a date with YYYYMMDD format.

I am trying the date, to_date, try_to_date, to_timestamp functions.

SELECT
	START_DATE AS START_DATE_ORIG,
	TRY_TO_DATE(START_DATE, 'YYYYMMDD') AS START_DATE
FROM MY_TABLE;

They either error with this.

SQL Error [100097] [22007]: Can't parse '12/1/2018 12:00:00 AM' as date with format 'YYYYMMDD'

Or show me this result with null values.

Snowflake日期从varchar转换

答案1

得分: 2

首先,您需要将您的varchar转换为日期格式,以正确解析日期值,然后可以将其再次输出为varchar,但要设置日期的输出格式。尝试这样做:

SELECT
    START_DATE AS START_DATE_ORIG,
    to_varchar(TO_DATE(START_DATE, 'MM/DD/YYYY HH12:MI:SS AM'), 'YYYYMMDD') AS START_DATE
FROM MY_TABLE;

我可能混淆了DDMM,请确保它符合您的本地首选项。

英文:

Firstly you need to convert your varchar to date format to parse properly the date value, then you can output it again to varchar, but setting the output format for date. Try this:

SELECT
    START_DATE AS START_DATE_ORIG,
    to_varchar(TO_DATE(START_DATE, 'MM/DD/YYYY HH12:MI:SS AM'), 'YYYYMMDD') AS START_DATE
FROM MY_TABLE;

I could mixed up DD and MM, make sure it is correct for your local preferences.

huangapple
  • 本文由 发表于 2023年6月8日 23:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定