日期字段文字与格式字符串不匹配

Date field literal does not match format string

我有一个名为 program_start_date 的字段,其格式为 YYYYMM。我需要确定这个日期是否发生在 5 年前或更短时间内,是否发生在 5 年前以上,或者它是否为空白。

我的 SQL 查询中有以下 case 语句:

CASE
   WHEN floor(MONTHS_BETWEEN(sysdate, program_start_date)/12) <= 5 THEN '5 years or less'
   WHEN floor(MONTHS_BETWEEN(sysdate, program_start_date)/12) > 5 THEN '6+ years'
   WHEN program_start_date is null THEN 'Blank'
   ELSE program_start_date
END

我收到以下错误消息:

ORA-01861: literal does not match format string 01861. 00000 - "literal does not match format string"
*Cause: Literals in the input must be the same length as literals in the format string (with the exception of leading whitespace). If the "FX" modifier has been toggled on, the literal must match exactly, with no extra whitespace.
*Action: Correct the format string to match the literal.

我尝试在前两种情况下插入 to_date(),但我仍然收到相同的错误消息。我该如何解决这个问题?

您的表达式隐式假定数据库的默认值 nls_date_format 与列的默认值相匹配,正如您所见,这根本不是真的 - 即使是这样,做出这种假设也是一种不好的做法,因为它使您的代码像蝴蝶翅膀一样脆弱。

相反,您应该使用 to_date 函数明确说明格式:

CASE
   WHEN floor(MONTHS_BETWEEN(sysdate, TO_DATE(program_start_date, 'YYYMM'))/12) <= 5 THEN '5 years or less'
   WHEN floor(MONTHS_BETWEEN(sysdate, TO_DATE(program_start_date, 'YYYMM'))/12) > 5 THEN '6+ years'
   WHEN program_start_date is null THEN 'Blank'
   ELSE program_start_date
END