ORACLE SQL單行函式細節

2021-09-17 03:09:29 字數 2465 閱讀 3756

單行函式有很多,不過有些經常用到又比較複雜(易忘)的概念或函式還是值得提出來做個筆記

首先是有關日期的運算都分先後的,比如:日期四則運算,months_between

select months_between(to_date('1997-7-7','yyyy-mm-dd'),sysdate) from dual
避免復合運算時遺漏的錯誤

取整函式round在數字上表現為0-9四捨五入,而時間上則是0-59與0-23對半分,星期則是7-6三舍四入,日期則是固定15舍16入,二月28日或29日,大小月30日或31日都是如此,在月份上則是六舍七入,

select round(to_date('2016-2-15','yyyy-mm-dd'),'month') a,

round(to_date('2016-2-16','yyyy-mm-dd'),'month') b,

round(to_date('2019-2-15','yyyy-mm-dd'),'month') a1,

round(to_date('2019-2-16','yyyy-mm-dd'),'month') b1,

round(to_date('2019-6-16','yyyy-mm-dd'),'year') c,

round(to_date('2019-7-15','yyyy-mm-dd'),'month') d,

round(to_date('2019-7-16','yyyy-mm-dd'),'month') e,

round(to_date('2019-7-18','yyyy-mm-dd'),'day') f,--星期四

round(to_date('2019-7-17','yyyy-mm-dd'),'day') f1,--星期三

round(to_date('2019-7-16 23:59:30','yyyy-mm-dd

hh24:mi:ss'),'dd') g,

round(to_date('2019-7-16 11:30:00','yyyy-mm-dd

hh24:mi:ss'),'hh') h,

round(to_date('2019-7-16 23:59:30','yyyy-mm-dd

hh24:mi:ss'),'mi') i

from dual

字元控制函式中的索引instr返回值為自然數,且起點為1,即當字串中沒有要查詢的字元時返回0而非空null

select instr('abcdefg','h'),instr('abcdefg','a') from dual
空值轉換函式中,nvl(exp,exp1)中exp型別要與exp1相同 ,coalesce(exp,exp1…)中exp型別也要相同,而nvl2(exp,exp1,exp2)中exp型別可不同exp1與2,返回值的型別則為轉換值型別

select nvl(commission_pct,1),

nvl2(commission_pct,'加倍',to_date('1997-7-7','yyyy-mm-dd'))

from employees

if_when_then格式的條件表示式有case_when_then外還有decode,而decode使用起來沒有case那麼靈活,其含義為decode(exp,exp1,val1,…valn),僅當exp1=exp返回val1,…,其餘返回valn

select commission_pct,decode(commission_pct,null,'空值','有值') from employees
sign函式根據返回值負數,零,正數返回-1,0,1,而對於空值則返回空值

select sign(commission_pct),sign(commission_pct-1),

commission_pct-1,commission_pct

from employees

日期擷取函式extract可用於取代to_char(date,『format』)獲取部分日期,不過只能年月日:p

select extract(day from to_date('1997-7-7','yyyy-mm-dd')) a,

extract(month from to_date('1997-7-7','yyyy-mm-dd')) b,

extract(year from to_date('1997-7-7','yyyy-mm-dd')) c

--extract(hour from to_date('1997-7-7','yyyy-mm-dd hh24:mi:ss')) d 錯誤示範

--extract(date from to_date('1997-7-7','yyyy-mm-dd hh24:mi:ss'))

from dual

ORACLE SQL單行函式

單行函式運算元據物件,接受引數返回乙個結果,只對一行資料進行變換,每行返回乙個結果,可以轉換資料型別,可以巢狀,引數可以是一列或乙個值 單行函式包括 字元函式 1 大小寫控制函式 lower 轉小寫 upper 轉大寫 initcap 首字母大寫 2 字元控制函式 concat 拼接字串 subst...

ORACLE SQL 單行函式

sql函式有兩種 1 單行行數 字元函式 數值函式 日期函式 轉換行數 通用行數 2 多行行數 字元行數 2.1大小寫控制函式 lower upper initcap 2.2字元控制函式 concat substr length instr lpad rpad trim replace 字元控制函式...

Oracle SQL單行函式之數字函式

數字函式 簡介 數字函式的輸入引數和返回值都是數字型別,並且多數函式精確到38位。函式cos cosh exp ln log sin sinh sqrt tan和tanh精確到36位,函式acos asin atan和atan2精確到30位。單行數字函式 1.abs n 該函式用於返回數字n的絕對值...