SQL to_date函数与案例查询

时间:2014-09-14 16:44:14

标签: sql oracle date

SQL Case可以显示操作,返回to_date函数的结果,作为其他条件的结果吗?

select m.movie_title,c.copy_id,
case 
when r.RENT_RETURN_DATE IS NULL
then 'not returned'
else (to_date(r.RENT_RETURN_DATE,'dd-mon-yyyy') -  to_date(r.RENT_DUE_DATE,'dd-mon-yyyy'))
end AS  "Days Late"
from  copy c,movie m,member mem,rental r
where mem.member_no=r.member_no and c.copy_id = r.copy_id 
and c.movie_id=m.movie_id and mem.member_no=102 

//(to_date(r.RENT_RETURN_DATE,'dd-mon-yyyy') - to_date(r.RENT_DUE_DATE,'dd-mon-yyyy'))----返回一个整数//

执行上述查询时,会显示以下错误:

  

错误报告 -

     

SQL错误:ORA-00932:不一致的数据类型:预期CHAR得到NUMBER   00932. 00000 - “不一致的数据类型:预期%s获得%s”

1 个答案:

答案 0 :(得分:1)

这里的问题是CASE语句中的两个分支返回不同的类型 - when返回一个字符串,而else返回一个整数。要解决此问题,您可以将else案例的返回值转换为字符串:

select m.movie_title,
       c.copy_id,
       case 
         when r.RENT_RETURN_DATE IS NULL then 'not returned'
         else TO_CHAR(to_date(r.RENT_RETURN_DATE, 'dd-mon-yyyy') -
                       to_date(r.RENT_DUE_DATE, 'dd-mon-yyyy'))
       end AS  "Days Late"
  from copy c,
       movie m,
       member mem,
       rental r
  where mem.member_no = r.member_no and
        c.copy_id = r.copy_id and
        c.movie_id = m.movie_id and
        mem.member_no = 102

分享并享受。