DB/오라클

[ORCLE]일반함수 NVL,DECODE,CASE-END....

에크키키 2022. 6. 24. 15:17

 

NULL은 연산과 비교를 하지못하므로 NVL 함수로 연산에 이용

NVL(값1, 값2) :

값1이 null이 아니면 값1 값이 null이면 값2

값1과 값2의 데이터타입은 일치해야한다.

NVL(commission,0)

 

NVL2(값1, 값2, 값3) :
값1,값1이 null이 아니면 값2, 값1이 null이면 값3)
1과 차이점: null이 아닐때 대체할 값을 정할 수 있다.

NVL2(commission,salary*12+commission,salary*12)

 

NULLIF(값1,값2):

두 값이 같으면 null, 다르면 '값1'

NULLIF('A','A') => null반환

NULLIF('A','B') => 'A' 

 

select ename, salary, commission,
salary*12+NVL(commission,0) as"연봉1",
salary*12+NVL2(commission,commission,0) as"연봉2",
nvl2(commission,salary*12+commission,salary*12) as "연봉3"
from employee;


select ename, salary, commission,
TO_CHAR(salary*12+NVL(commission,0),'L999,999,999') as"연봉1",
TO_CHAR(salary*12+NVL2(commission,commission,0),'L999,999,999') as"연봉2",
TO_CHAR(NVL2(commission,salary*12+commission,salary*12),'L999,999,999') as "연봉3"
from employee;--format과 함께사용

select nullif('A','A'), nullif('A','B')
from dual;

coalesce(인수, 인수, 인수................)

 인수 중에서 null이 아닌 첫번째 인수 반환 

select ename,salary,commission,
coalesce(commission,salary,0) -- commission이 null이 아니면 commission출력,
----------------------------salary가 null이 아니면 salary , 모두 null 이면 0
from
employee;

decode()

자바의 switch문과 비슷 가장많이사용

 

select ename,dno,
decode (dno,10,'ACCOUNTING',
           20,'RESEARCH',
           30,'SALES',
           40,'OPERATIONS',
           'default')--일치하는 값이 없거나 null인 경우
           as dname --별칭, 칼럼이 아님
from employee
order by dno asc ;

--dno가10이면accounting으로 대체,20이면 research........


select eno,ename,job,salary,
decode(job,'ANALIST',salary+200,
	   'SALESMAN',salary+180,
           'MANAGER',salary+150,
           'CLERK',salary+100,
           salary)as update_salary
 from employee;

case~end

자바의 if-else if 문과 비슷

사이에 ' , '없음 주의

decode()함수에서 사용하지 못하는 비교연산자 중  =(같다) 제외한 나머지 다양한 비교연산자(>= ,<= ,> ,< ,!=)을 사용가능

 

select ename,dno,
CASE when dno=10 then 'ACCOUNTING'
     when dno=20 then'RESEARCH'
     when dno=30 then 'SALES'
     when dno=40 then 'OPERATIONS'
     else 'default' --일치하는 값이 없거나 null인경우 
END as dname--별칭
from employee
order by dno asc ;