17,377
社区成员
发帖
与我相关
我的任务
分享
--要么是你的日期字段存得有问题,要么是你的查询语句写得有问题:
--下面是例证:
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
-- 再用 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;
---------------------------- 先创建一个is_date()的函数 -----------------------------------
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;
-- 为什么:这样的问题,天天有人问呢?
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;
-- 为什么:这样的问题,天天有人问呢?