学习内容:
1、掌握各种在pl/sql中可用的函数
2、使用这些函数的基本概念
3、select语句中使用函数
4、使用转换函数
一、function的作用:
进行数据计算,修改独立的数据,处理一组记录的输出,不同日期显示格式,进行数据类型转换
函数分为:单独函数(row)和分组函数
注意:可以嵌套、可以在select, where, 和 order by中出现。
语法:function_name (column|expression, [arg1, arg2,])
二、字符型函数
1、lower 转小写
2、upper 转大写
3、initcap 首字母大写
4、concat 连接字符,相当于 ||
5、substr substr(column|expression,m[,n])
6、substrb substrb(column|expression,m[,n])
7、length 返回字符串的长度
8、nvl 转换空值
9、decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
其中,1、2经常用来排杂,也就是排除插入值的大小写混用的干扰,如:
sql> select first_name, last_name
2 from s_emp
3 where upper(last_name) = ’patel’;
first_name last_name
-------------------- --------------------
vikram patel
radha patel
四、oracle 日期格式和日期型函数:
三、数学运算函数
1、round
四舍五入:round(45.923,2) = 45.92
round(45.923,0) = 46
round(45.923,-1) = 50
2、trunc
截取函数
trunc(45.923,2)= 45.92
trunc(45.923)= 45
trunc(45.923,-1)= 40
3、mod 余除
mod(1600,300)
实例:
sql> select round(45.923,2), round(45.923,0),
2 round(45.923,-1)
3 from sys.dual;
四、oracle 日期格式和日期型函数:
dual
五、转换函数:
1、to_char
使一个数字或日期转换为char
2、to_number
把字符转换为number
3、to_date
字符转换为日期
这几个函数较为简单,但要多多实践,多看复杂的实例。
sql> select id,to_char(date_ordered,’mm/yy’) ordered
2 from s_ord
3 where sales_rep_id = 11;
转换时,要注意正确的缺省格式:
select to_date('03-mar-92') correct from dual;//正确
select to_date('031092') correct from dual;//不正确
select to_date('031095','mmddyy') errorr from dual
输出 3月10日
select to_date('031095','ddmmyy') errorr from dual
输出 10月3日
4、实例:
select to_char(sysdate,'fmddspth "of" month yyyy am') todays from dual;
todays
--------------------------------
sixteenth of 11月 2001 下午
大小写没有什么影响,引号中间的是不参与运算。
实例 :
select round(salary*1.25) from one_table;
意义:涨25%工资后,去除小数位。在现实操作中,很有意义。
5、混合实例:
sql> select last_name, to_char(start_date,
2 ’fmdd ”of” month yyyy’) hiredate
3 from s_emp
4 where start_date like ’%91’;
last_name hiredate
------------ --------------------
nagayama 17 of june 1991
urguhart 18 of january 1991
havel 27 of february 1991
这里要注意:fmdd 和 fmddspth之间的区别。
sql> select id, total, date_ordered
2 from s_ord
3 where date_ordered =
4 to_date(’september 7, 1992’,’month dd, yyyy’);
六、独立的函数嵌套
sql> select concat(upper(last_name),
2 substr(title,3)) ”vice presidents”
3 from s_emp
4 where title like ’vp%’;
* 嵌套可以进行到任意深度,从内向外计算。
例:
sql> select to_char(next_day(add_months
2 (date_ordered,6),’friday’),
3 ’fmday, month ddth, yyyy’)
4 ”new 6 month review”
5 from s_ord
6 order by date_ordered;
sql> select last_name,
2 nvl(to_char(manager_id),’no manager’)
3 from s_emp
4 where manager_id is null;
对于例子,大家重要的理解,并多做测试,并注意英文版和中文版在日期上的区别。
有些教材上的例子,不要盲目的相信其结果,实践后才有发言权,希望大家能够在学习的过程中不要忽略了用,
多想一想为什么实例要如此设计,在何种情况下应用此实例来解决问题。这样,我们才真正掌握了知识。