我正试图从MON-YY'格式化,然后将获取的年份与' 01-JUN' 。我曾经用to_date强制转换字符串' (' 01-JUN-17')到' date'类型 以下代码在特定数据库中工作正常,例如db_1
select to_date('01-JUN-'||(EXTRACT(YEAR FROM to_date('MAY-17','mon-yy'))) ) AS YEAR_START_DATE from dual;
返回:
01-JUN-17
但在db_2中,相同的代码会抛出以下错误:
ORA-01858: a non-numeric character was found where a numeric was expected
01858. 00000 - "a non-numeric character was found where a numeric was expected"
*Cause: The input data to be converted using a date format model was
incorrect. The input data did not contain a number where a number was
required by the format model.
*Action: Fix the input data or the date format model to make sure the
elements match in number and type. Then retry the operation.
有人可以帮忙吗?
答案 0 :(得分:1)
'01-JUN-' || EXTRACT(YEAR FROM to_date('MAY-17','mon-yy'))
将生成类似'01-JUN-2017'
如果在未指定格式模型的情况下尝试使用TO_DATE( datestring, format_model )
,则会出现此问题。在这种情况下,查询将使用NLS_DATE_FORMAT
会话参数。
您可以使用以下方法找到此值:
SELECT VALUE
FROM SYS.NLS_SESSION_PARAMETERS
WHERE PARAMETER - 'NLS_DATE_FORMAT';
如果这与您指定的格式不匹配,则会引发异常。
您应该明确指定格式模型(和语言):
SELECT TO_DATE(
'01-JUN-'||EXTRACT(YEAR FROM to_date('MAY-17','mon-yy','NLS_LANGUAGE="ENGLISH"')),
'dd-MON-YYYY',
'NLS_LANGUAGE="ENGLISH"'
) AS YEAR_START_DATE
FROM DUAL;
或者您可以使用:
SELECT ADD_MONTHS(
TRUNC(
TO_DATE( 'MAY-17', 'MON-YY', 'NLS_LANGUAGE="ENGLISH"' ),
'YY'
),
5
) AS YEAR_START_DATE
FROM DUAL;
答案 1 :(得分:0)
您缺少第一个to_date(' 01-JUN - ' ..)功能的日期格式。一个数据库的日期格式可能是DD-MON-YYYY,但在另一个数据库中可能是DD-MM-YYYY。
添加日期格式后,您的查询如下所示:
select to_date('01-JUN-' || (extract(year from to_date('MAY-17', 'mon-yy'))),'DD-MON-YYYY') as year_start_date
from dual;
在将日期转换为字符串时始终指定格式是一种很好的做法。