表中有字段 a_time varchar(40) ,存储数据为日期格式数据(例如:2011-5-10 10:30:23 ),
想要将该字段作为日期条件查询:to_date(a_time,'yyyy-mm-dd hh24:mi:ss') >= to_date('2010-05-26'||' 00:00:00','yyyy-mm-dd hh24:mi:ss') 但是报输入格式有错,求方法
想要将该字段作为日期条件查询:to_date(a_time,'yyyy-mm-dd hh24:mi:ss') >= to_date('2010-05-26'||' 00:00:00','yyyy-mm-dd hh24:mi:ss') 但是报输入格式有错,求方法
你的比较方法没问题· tangren是说 你的 a_time 里面可能有不是日期格式的值
--要么是你的日期字段存得有问题,要么是你的查询语句写得有问题:
--下面是例证:
SQL> with t as(
2 select 1 id,'2011-01-01 10:30:23' dt from dual union all
3 select 2,'2000-05-15 10:56:00' from dual union all
4 select 3,'2008-08-09 06:00:00' from dual)
5 select id,
6 case
7 when to_date(dt,'yyyy-mm-dd hh24:mi:ss') >=
8 to_date('2007-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')
9 then 'Greater than or equal'
10 else 'Less than'
11 end dt
12 from t
13 / ID DT
---------- ---------------------
1 Greater than or equal
2 Less than
3 Greater than or equal
--
SQL> with t as(
2 select 1 id,'2011-01-01 10:30:23' dt from dual union all--即使有空格也没问题
3 select 2,' 2000-05-15 10:56:00' from dual union all
4 select 3,'2008-08-09 06:00:00 ' from dual)
5 select id,
6 case
7 when to_date(dt,'yyyy-mm-dd hh24:mi:ss') >=
8 to_date('2007-01-01'||'00:00:00','yyyy-mm-dd hh24:mi:ss')--即使字符串连接组成日期,也没问题
9 then 'Greater than or equal'
10 else 'Less than'
11 end dt
12 from t
13 / ID DT
---------- ---------------------
1 Greater than or equal
2 Less than
3 Greater than or equal
不大的话 把a_time的值都查出来看看 估计有些值不符合要求
sql基本上是没问题的 数据有问题的可能性很大
你在to_date(a_time,'yyyy-mm-dd hh24:mi:ss') >= to_date('2010-05-26'||' 00:00:00','yyyy-mm-dd hh24:mi:ss') 后边加上一个 and rownum = 1 再查询一次看看,如果没问题就说明sql没问题,是数据问题
return number
is
v_date date;
begin
-- to_date(i_str,'yyyy-mm-dd hh24:mi:ss') 中的 'yyyy-mm-dd hh24:mi:ss' 是你的字符类型存储日期的格式!(你可以根据你的数据进行修改其格式)
select to_date(i_str,'yyyy-mm-dd hh24:mi:ss') into v_date from dual;
if v_date is not null then
return 1;
else
return 0;
end if;
EXCEPTION
WHEN OTHERS
THEN
return 0;
end;
/-- 再用 is_date()查一下,看是否存在其他非法(或日期格式不一样)的数据!select * from tb_name where is_date(a_time)=0;-- 为什么:这样的问题,天天有人问呢?
create or replace function is_date(i_str varchar2)
return number
is
v_date date;
begin
-- to_date(i_str,'yyyy-mm-dd hh24:mi:ss') 中的 'yyyy-mm-dd hh24:mi:ss' 是你的字符类型存储日期的格式!(你可以根据你的数据进行修改其格式)
select to_date(i_str,'yyyy-mm-dd hh24:mi:ss') into v_date from dual;
if v_date is not null then
return 1;
else
return 0;
end if;
EXCEPTION
WHEN OTHERS
THEN
return 0;
end;
/-- 再用 is_date()查一下,看是否存在其他非法(或日期格式不一样)的数据! select * from tb_name where is_date(a_time)=0; -- 为什么:这样的问题,天天有人问呢?
select * from tb_name where is_date(a_time)=0 or a_time is not null;