1. 程式人生 > >Oracle基礎知識(6)--函式

Oracle基礎知識(6)--函式

--oracle的函式
--函式可以巢狀呼叫
*字元函式:處理字串
--ascii chr
select ascii('a') from dual;
select chr(97) from dual;
--lower,upper
--求A的ASCII碼
select ascii(upper('a')) from dual;
--求a的ASCII碼
select ascii(lower('A')) from dual;


--intcap:第一個字元大寫,其他字元小寫
select initcap(ename) from emp;


--ltrim,rtrim,trim
--ltrim,rtrim是字元級別的擷取,在截斷的時候,按照字元去匹配
select ltrim('elaleellen','el') from dual; 
select rtrim('ellenellneen','ne') from dual;
--trim的擷取集是一個字元
select trim('e' from 'ellenellnee') from dual;
select trim('   ellen   ')from dual;--去掉兩邊的空格


--lpad,rpad:字串
select lpad('hao',2,'ni') from dual;
select lpad('hao',5,'ni') from dual;
select lpad('hao',9,'ni') from dual;


select rpad('ni',1,'hao') from dual;
select rpad('ni',5,'hao') from dual;
select rpad('ni',8,'hao') from dual;


--其他:concat,length,substr,replace
--字串連結,和連線運算子作用接近
select concat('Dear ',ename) from emp;
--length:查詢empt表中員工姓名為5個字元的員工的資訊
select * from emp where length(ename)=5;
--substr:求子串
select substr('hello world',3,5) from dual;
select substr('hello world',3) from dual;
--replace:替換
select replace('shelly','el','en') from dual;


*數字函式
--sign:求符號
select sign(-5) from dual;
--ceil:向上取整
select ceil(5.6) from dual;
--floor:向下取整
select floor(5.6) from dual;
--round:四捨五入
select round(3.5) from dual;
select round(356,-2) from dual;
--trunc:截斷
select trunc(3.1415926,4) from dual;
select trunc(356,-2) from dual;


*日期函式
--sysdate systimestamp
select sysdate from dual;
select systimestamp from dual;
--add_months
select add_months(sysdate,1) from dual;
--months_between(date,date)
select months_between(sysdate,hiredate) from emp;
select months_between(sysdate,add_months(sysdate,1)) from dual;
--last_day(date)
select last_day(sysdate) from dual;
select last_day('08-2月-2018') from dual;
--next_day(date,char)
select next_day(sysdate,'星期一') from dual;
--round,trunc
select trunc(sysdate,'MONTH') from dual;
select round(sysdate,'MONTH') from dual;
select round(date'2018-01-16','MONTH') from dual;
--extract:
select extract(year from sysdate) as 年,
extract(month from sysdate) as 月,
extract(day from sysdate) as 日,
extract(hour from systimestamp) as 時,
extract(minute from systimestamp) as 分,
extract(second from systimestamp) as 秒
from dual;


*轉換函式
--to_char to_date
--nvl nvl2
--問題:對emp表中員工,如果獎金為空,給200元獎金,如果獎金不為空,那麼在原有獎金基礎上加100
update emp01 set comm=nvl2(comm,comm+100,200);
--問題:查詢emp表中所有員工的月收入
select ename,sal+nvl(comm,0) as 月收入 from emp;
select ename,coalesce(sal+comm,sal) as 月收入 from emp;
--decode
--案例:按照職位提升工資,如果是manager,工資是原來的1.5倍,如果是ANALYST,工資是原來的1.2倍
--如果是SALESMAN,工資是原來的1.1倍,否則工資是原來的1.05倍
update emp01 set sal=decode(job,'MANAGER',sal*1.5,
'ANALYST',sal*1.2,'SALESMAN',sal*1.1,sal*1.05);