我有这个表,其中VARCHAR2(128 CHAR)字段的格式可以是2018-01-01 00:00:00
或01/01/2018 00:00:00
或01-JAN-2018 00:00:00
如何仅以2016-01-01 00:00:00
或01-JAN-2018 00:00:00
格式提取包含VARCHAR2(128 CHAR)字段的记录?
答案 0 :(得分:1)
不好在varchar中存储日期。但就像这样,我建议将字符串转换为日期,然后再将字符串转换为字符串。像这样:
declare
d date;
begin
begin
d:=to_date('01.01.2011 23:49:00','dd/mm/yyyy hh24:mi:ss');
exception
when others then
begin
d:=to_date('01.01.2011 23:49:00','dd.mm.yyyy hh24:mi:ss');
exception
when others then
begin
d:=to_date('01.01.2011 23:49:00','dd-mm-yyyy hh24:mi:ss');
exception
when others then
-- any more date format strings?
null;
end;
end;
end;
dbms_output.put_line(to_char(d,'dd-mm-yyyy hh24:mi:ss'));
end;
/
答案 1 :(得分:1)
创建一个将日期字符串转换为日期的函数:
create or replace function date_from_string(str varchar2, fmt varchar2) return date is
v date;
begin
return to_date(str,fmt);
exception when others
then return null;
end;
查询表格,例如:
with t as (
select case when regexp_like(field, '^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$')
then 'YYYY-MM-DD HH24:MI:SS'
when regexp_like(field, '^\d\d-[a-zA-Z]{3}-\d{4} \d\d:\d\d:\d\d$')
then 'DD-MON-YYYY HH24:MI:SS'
end fmt, t.*
from "TABLE" t
)
select t.*, date_from_string(t.field, t.fmt) "DATE" from t
where date_from_string(t.field, t.fmt) is not null;
通过这种方式,您可以轻松检查给定记录中的日期是否正确。