oracle使用nullif解決除數(shù)為零的問題分析
oracle使用nullif解決除數(shù)為零
說一下nullif的語法

NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.
If both arguments are numeric data types, then Oracle Database determines the argument with the higher numeric precedence, implicitly converts the other argument to that data type, and returns that data type. If the arguments are not numeric, then they must be of the same data type, or Oracle returns an error.
The NULLIF function is logically equivalent to the following CASE expression:
CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END
如果兩個參數(shù)相等,返回null,否則返回第一個。
第一個參數(shù)不可指定為空。對于非數(shù)字類型參數(shù),數(shù)據(jù)類型必須一致。對于數(shù)值數(shù)據(jù)類型,會隱式的轉(zhuǎn)化為更高優(yōu)先級的數(shù)據(jù)類型。(這個理解可能有誤,我測試了int,integer,float。但是最終都轉(zhuǎn)化為number類型)。
一般來說
我們處理“除數(shù)為零”的問題會用到decode(當(dāng)然也可以用case,但是寫起來代碼更多些)。
比如:
dividend / decode(divisor, 0, null, divisor)
但是在除數(shù)divisor非常復(fù)雜的時候,就需要把這一大串代碼寫兩遍,或者是再套一層view。
無論是哪種,都是極其不利于維護的。
1 /
decode((sum(t.val) over(order by t.c) +
nvl(lead(val) over(partition by b order by c), 0)) /
sum(val) over(partition by b order by c),
0,
null,
(sum(t.val) over(order by t.c) +
nvl(lead(val) over(partition by b order by c), 0)) / sum(val)
over(partition by b order by c))對于這種復(fù)雜表達式的除數(shù),每回修改都要改兩遍,很容易出錯。
利用nullif,可以讓除數(shù)只寫一次。
因為 decode(divisor, 0, null, divisor) 與 nullif(divisor, 0) 是等效的。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
處理Oracle監(jiān)聽程序當(dāng)前無法識別連接描述符中請求的服務(wù)異常(ORA-12514)
這篇文章介紹了處理Oracle監(jiān)聽程序當(dāng)前無法識別連接描述符中請求的服務(wù)異常(ORA-12514),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
一次簡單的Oracle恢復(fù)Case實戰(zhàn)記錄
這篇文章主要給大家介紹了一次簡單的Oracle恢復(fù)Case實戰(zhàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-10-10
Oracle數(shù)據(jù)塊實現(xiàn)原理深入解讀
Oracle對數(shù)據(jù)庫數(shù)據(jù)文件(datafile)中的存儲空間進行管理的單位是數(shù)據(jù)塊(data block),本文將詳細介紹2012-11-11
Oracle中ORA-01489:字符串連接的結(jié)果過長問題三種解決辦法
使用LISTAGG函數(shù)拼接字符串超過VARCHAR2長度會報ORA-01489錯誤,這篇文章主要介紹了Oracle中ORA-01489:字符串連接的結(jié)果過長問題的三種解決辦法,需要的朋友可以參考下2025-07-07
Oracle實現(xiàn)行列轉(zhuǎn)換的方法分析
這篇文章主要介紹了Oracle實現(xiàn)行列轉(zhuǎn)換的方法,結(jié)合實例形式分析了Oracle針對固定列、不定列、列數(shù)不固定等情況下的行列轉(zhuǎn)換操作技巧,需要的朋友可以參考下2016-08-08
oracle 存儲過程和觸發(fā)器復(fù)制數(shù)據(jù)
oracle 存儲過程和觸發(fā)器復(fù)制數(shù)據(jù)的代碼,需要的朋友可以參考下。2009-11-11
Oracle?DML觸發(fā)器和DDL觸發(fā)器實例詳解
Oracle觸發(fā)器是使用者對Oracle數(shù)據(jù)庫的對象做特定的操作時,觸發(fā)的一段PL/SQL程序代碼器,下面這篇文章主要給大家介紹了關(guān)于Oracle?DML觸發(fā)器和DDL觸發(fā)器的相關(guān)資料,需要的朋友可以參考下2023-03-03

