DECODE() Function는 return된 결과가 지정된 값과 동일할 경우 특정 value를 출력해주는 function이다. DECODE()는 다음과 같은 형태로 사용된다.
DECODE(value, search_value, result, default_value)
위의 decode function은 미리 지정된 value와 search_value가 같을 경우 result를, 그렇지 않은 경우 default_value를 출력한다. 이와 같이 decode()는 SQL에서 PL/SQL없이 IF-THEN-ELSE logic을 구현하고 있다.
다음은 decode()의 간단한 동작 예이다.
SELECT DECODE(1, 1, 2, 3)
FROM dual;
DECODE(1,1,2,3)
---------------
2
SELECT DECODE(1, 2, 1, 3)
FROM dual;
DECODE(1,2,1,3)
---------------
3
FROM dual;
DECODE(1,1,2,3)
---------------
2
SELECT DECODE(1, 2, 1, 3)
FROM dual;
DECODE(1,2,1,3)
---------------
3
다음의 예는 more_products table의 available column의 값을 비교해 원하는 string을 출력한다. available column의 값이 'Y'일 경우 "Product is available'을 출력하고, 'Y'가 아닐 경우 'Product is not available"을 출력한다.
SELECT prd_id, available,
DECODE(available, 'Y', 'Product is available',
'Product is not available')
FROM more_products;
PRD_ID A DECODE(AVAILABLE,'Y','PR
---------- - ------------------------
1 Y Product is available
2 Y Product is available
3 N Product is not available
4 N Product is not available
5 Y Product is available
DECODE(available, 'Y', 'Product is available',
'Product is not available')
FROM more_products;
PRD_ID A DECODE(AVAILABLE,'Y','PR
---------- - ------------------------
1 Y Product is available
2 Y Product is available
3 N Product is not available
4 N Product is not available
5 Y Product is available
다음은 product table의 product_type_id column의 값들에 따라 원하는 string을 출력한다. 즉 product_type_id가 1일 경우 'Book', 2일 경우 'Video', 3일 경우 'DVD', 4일 경우 'CD', 기타 다른 값일 경우 'Magazine'을 출력한다.
SELECT product_id, product_type_id,
DECODE(product_type_id,
1, 'Book',
2, 'Video',
3, 'DVD',
4, 'CD',
'Magazine')
FROM products;
PRODUCT_ID PRODUCT_TYPE_ID DECODE(P
---------- --------------- --------
1 1 Book
2 1 Book
3 2 Video
4 2 Video
5 2 Video
6 2 Video
7 3 DVD
8 3 DVD
9 4 CD
10 4 CD
11 4 CD
12 Magazine
DECODE(product_type_id,
1, 'Book',
2, 'Video',
3, 'DVD',
4, 'CD',
'Magazine')
FROM products;
PRODUCT_ID PRODUCT_TYPE_ID DECODE(P
---------- --------------- --------
1 1 Book
2 1 Book
3 2 Video
4 2 Video
5 2 Video
6 2 Video
7 3 DVD
8 3 DVD
9 4 CD
10 4 CD
11 4 CD
12 Magazine
Decode()은 CASE문에 비해 depth가 깊어지면 성능이 떨어지는 것으로 알려져 있다. depth가 깊은 SQL의 경우 CASE()와의 성능 비교가 필요할 수 있다.
* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!
'Oracle Database' 카테고리의 다른 글
Oracle in the Cloud (1) | 2010.04.09 |
---|---|
Oracle 내 table에 걸쳐있는 constraint 찾고, disable 하기 (0) | 2010.04.06 |
Oracle Active DataGuard Monitoring script (0) | 2010.03.31 |
Oracle 전문가가 되기위한 추천 책,자료 (0) | 2010.03.30 |
Oracle FLASHBACK TABLE - sample (2) | 2010.03.30 |