1. 程式人生 > >ORACLE函式之空值

ORACLE函式之空值

NVL、NVL2、NULLIF、COALESCE
NVL
SELECT employee_id,salary,commission_pct,salary+salarycommission_pct FROM employees;
SELECT employee_id,salary,commission_pct,salary+salary
NVL(commission_pct,0) FROM employees;
在這裡插入圖片描述
在這裡插入圖片描述
nvl(exp1,exp2) exp1為空值輸出exp2 非空輸出原值
SELECT employee_id,salary,commission_pct,salary+salary*NVL(commission_pct,‘ABC’) FROM employees;注意參與運算時一定要讓引數個數相同,不然會報錯

NVL2
SELECT employee_id,salary,commission_pct,salary+salary*NVL2(commission_pct,‘sal+comm’,‘sal’) FROM employees;錯誤

SELECT employee_id,salary,commission_pct,NVL2(commission_pct,‘sal+comm’,‘sal’) FROM employees;
在這裡插入圖片描述
nvl2(exp1,exp2,exp3)如果exp1為空值輸出exp3,若為非空,輸出exp2

NULLIF
SELECT length(first_name),length(last_name),nullif(length(first_name),length(last_name)) “Res” FROM employees;
在這裡插入圖片描述


nullif(exp1,exp2)exp1等於exp2時為空值 否則輸出exp1

COALESCE
SELECT first_name,commission_pct,manager_id,COALESCE(commission_pct,manager_id,‘NO commission and no manager’) FROM employees;錯誤格式不統一
SELECT first_name,commission_pct,manager_id,COALESCE(TO_CHAR(commission_pct),TO_CHAR(manager_id),‘NO commission and no manager’) FROM employees;需要to_char轉化一次
在這裡插入圖片描述


COALESCE(exp1,exp2,…expn)如果exp1為空 則繼續看exp2, 直到不為空輸出結果