日期:2014-05-16  浏览次数:20323 次

几个 Oracle 常用函数 实例 运用
针对Oracle数据库特有的函数,不包括SQL本身就有的。几个常用的Oracle函数:nvl、to_char、to_date、to_number、trim、length、substr、等等

 select nvl(sum(c.f_factplan),0) f_factplan from pay_certificate c left join pay_reporting r on r.f_id=c.f_repid where to_number(r.f_year||trim(to_char(r.f_month,'09')))<(select to_number(r.f_year||trim(to_char(r.f_month,'09'))) yearmonth from pay_certificate t left join pay_reporting r on r.f_id=t.f_repid where t.f_id=7) and c.f_ctrid=15


上面这条sql语句综合运用了好几个函数,这里,我们不考虑这条SQL语句的业务,只单纯的从SQL出发。to_char(r.f_month,'09'),将f_month字段中的月份每个都转换为两位长度,这种写法可能是因为f_month字段定义成了数字型,但是在查询中,又需要将它与年份组合成一个形如yyyymm格式的数字来进行大小的比较,这个例子就是如此,trim去掉组合后前后空格,然后用||操作符将它与年组合起来转换为数字。


-------------------------
这条SQL语句主要运用的就是to_date函数,记注意这里的小时、分、秒,与我们平时的yyyy-MM-dd HH:mm:ss的写法不一样,我们现在的时间一般都是使用24小时制,所以这里要写成hh24,如果是12小时制就去掉24

select * from dtaq_data d inner join dtaq_data_info i on d.info_id=i.info_id where d.point_id = 1199 and i.info_type='T' and d.write_date <= to_date('2008-11-21 23:59:59','yyyy-mm-dd hh24:mi:ss')


---------------------------
when...then...else,length函数判断字符串的长度,substr对字符串进行截取,注意起始位置的索引为1,这和我们一般认为的0开始不一样。

select a.f_id,a.f_name from orgaizeation a inner join (select case when length(o.f_nodecode)>8 then substr(o.f_nodecode,1,8) else o.f_nodecode end f_nodecode from orgaizeation o where o.f_id = 23) b on a.f_nodecode=b.f_nodecode order by b.f_nodecode


--------------------------