三、单行函数

三、单行函数

两种类型函数:
单行函数:single-row-functions  每行返回一个结果
多行函数:multiple-row-functions  每个行组集返回一个结果

单行函数:
1、使用函数为了操作数据
2、将输入的变量处理,每行返回一个结果
3、可以转换数据类型,可以嵌套使用
4、传入的变量可以是列值,也可以是表达式

字符函数:
大小写类型:case-conversion-functions
lower 大写变成小写
upper 小写变成大写
initcap 将首字母大写,其他字母小写
SQL> select ename,sal,job from emp where ename=upper('smith');
SQL> select ename,sal,job from emp where lower(ename)='smith';
建议使用第一种,因为第二种是对表内所有的名字变成小写之后与smith比较,如果表中条目很多的话会影响数据库运行
一般在等号的右边使用函数

字符处理类型:character-manipulation-functions
concat 拼接
concat ('hellow','world') 
helloworld

substr 截取
substr('helloword',1,5) 
hellow

length 求字符长度
length('helloworld')
10

instr 查看字符是第几个
instr('helloworld','w')
6

lpad | rpad 在左边用字符补充成为X个字符 | 在右边用字符补充成为X个字符
lpad(sal,10,'*')
******1000
rpad(sal,10,'*')
1000******

replace 将字符替换
replace ('jack and jue' ,'j','bl')
black and blue

trim 去除字符
trim('h' from  'helloworld')
elloworld 
trim(' ' from ' helloworld   ')  去空格
helloworld

数字函数:number functions
round  按照指定小数四舍五入
SQL> select round(  ,  ) from dual;
括号前半部分表示要四舍五入的数字
括号后半部分表示位数,以小数点为界限,
-2代表小数点前二位以后都四舍五入
2代表小数点后数两位,之后的数字四舍五入
0或者不输入代表小数后四舍五入

trunc  按照指定小数截断数据
SQL> select trunc (  ,  ) from dual;
括号前表示要截取的数字
括号后表示截取的位数,以小数点为界限,
-2代表小数点前二位以后都都删去
2代表小数点后数两位,之后的数字删去
0或者不输入表示小数点以后的数字都删除

mod  两数相除取余数
两数相除取余数
SQL> select mod (2,0) from dual;
  MOD(2,0)
----------
     2
SQL> select mod (0,0) from dual;
  MOD(0,0)
----------
     0
SQL> select mod (2) from dual;
select mod (2) from dual
       *
ERROR at line 1:
ORA-00909: invalid number of arguments

0可以被mod取余数时除,但是不可以被除以

SQL> select 1/0 from dual;
select 1/0 from dual
        *
ERROR at line 1:
ORA-01476: divisor is equal to zero

日期:working with dates
Oracle数据库默认显示日期格式:世纪,年,月,日,时,分秒
默认显示: DD-MON-RR
默认显示年的最后2个数字

日期算术运算:arithmetic with dates
1、现有日期加上或者减去一个数值,可以得到一个新的日期
2、两个日期相减,得到两个日期间的天数
3、除以24,可以得到小时数
select ename,(sysdate-hiredate)/7 as weaks from emp
where deptno=10;
查看出10部门所有人分别工作了多少周

日期函数处理:
months_between ('01-sep-19,'11-jan-18')  两个日期之间相差多少月
add_mounth ('30-jan-96',1)   日期加一个月
next_day ('01-sep-95','friday')  下一个周五
last_day ('01-feb-95')  这个月的最后一天

舍入与截断
round (sysdate,'mounth')   按月份四舍五入
round(sysdate,'year')   按年份四舍五入
trunc(sysdate,'month')  按月份截取
trunc(sysdate,'year')   按年份截取

猜你喜欢

转载自blog.csdn.net/weixin_43403578/article/details/89225014