ORACLE中to_char、to_date、trunc、to_number、cast函數(shù)

一、to_char

to_char函數(shù)的功能是將數(shù)值型或者日期型轉(zhuǎn)化為特定格式的字符型

1、將日期轉(zhuǎn)化為年月日格式

select to_char(sysdate,'yyyy-MM-dd') ,sysdate from dual; 
oracle中默認(rèn)日期格式是年月日時(shí)分秒

2、將日期轉(zhuǎn)化為年月日,星期幾格式

select to_char(sysdate,'yyyy-MM-dd day') ,sysdate from dual; 


3、提取日期格式中的年、月、日、時(shí)間

select to_char(sysdate,'YYYY')as 年,to_char(sysdate,'mm')as 月 ,to_char(sysdate,'dd')as 日,
to_char(sysdate,'hh24')as 小時(shí),sysdate from dual; 


4、將小數(shù)轉(zhuǎn)化為特定格式的字符串

select TO_CHAR(15000,'$99,999.99') from dual
select TO_CHAR(15000.8923,'99999.00'),
to_char(82.365982356,'FM099.9900'),
to_char(82,'0999.00'),
to_char(82.98784567,'999.9999')from dual
  • 0表示:如果參數(shù)(double或者float類型)存在數(shù)字就顯示數(shù)字,不存在數(shù)字就顯示0
  • 9表示:如果參數(shù)(double或者float類型)存在數(shù)字就顯示數(shù)字,不存在數(shù)字就顯示空格
  • FM表示:將9帶來的空格刪除

3、to_char10進(jìn)制轉(zhuǎn)化為16進(jìn)制

select to_char(4567,'xxxx') from dual;

二、to_date

將字符串轉(zhuǎn)化為日期格式

select to_date('2018-9-8','yyyy-mm-dd'),
to_date('2019-08-07 23:25:59','yyyy-MM-dd HH24:mi:ss'),
to_date('2019-08-07 23:25:59','yyyy-MM-dd HH24:mi:ss')-30,
to_date('2019-08-07 23:25:59','yyyy-MM-dd HH24:mi:ss')-6/24
from dual

三、trunc

trunc()函數(shù)是對(duì)時(shí)間類型或者數(shù)字進(jìn)行截取操作的,返回的時(shí)間或者數(shù)字類型
1、時(shí)間

select  trunc(sysdate,'yyyy') from   dual ;--返回當(dāng)年第一天
select  trunc(sysdate,'mm') from   dual ; --返回當(dāng)月第一天
select  trunc(sysdate,'dd') from   dual ;--返回當(dāng)前年月日
select  trunc(sysdate,'d') from   dual ; --返回當(dāng)前星期的第一天(星期日) 
select  trunc(sysdate,'hh') from   dual ;--返回當(dāng)前日期截取到小時(shí),分秒補(bǔ)0
select  trunc(sysdate,'mi') from   dual ;--返回當(dāng)前日期截取到分,秒補(bǔ)0


2、數(shù)字
TRUNC(number,num_digits)
Number 需要截尾取整的數(shù)字。
Num_digits 用于指定取整精度的數(shù)字。Num_digits 的默認(rèn)值為 0。
TRUNC()函數(shù)截取時(shí)不進(jìn)行四舍五入

select trunc(123.458) from dual --123
select trunc(123.458,0) from dual --123
select trunc(123.458,2) from dual --123.45
select trunc(123.458,-1) from dual --120
select trunc(123.458,-2) from dual --100
  • ROUND—按照指定的精度進(jìn)行四舍五入
select round(3.1415926,4) from dual;
  • FLOOR——對(duì)給定的數(shù)字取整數(shù)位
select floor(2345.67) from dual;

四、cast

CAST()函數(shù)可以進(jìn)行數(shù)據(jù)類型的轉(zhuǎn)換。

 select cast(123.56 as int) from dual --124
 select cast('123.56' as int) from dual --124

五、to_number

主要是將字符串轉(zhuǎn)換為數(shù)值型的格式,與TO_CHAR()函數(shù)的作用正好相反。

select to_number('123.45') + 2 from dual; --125.45
SELECT TO_NUMBER('$12,123.23','$999,999.99') FROM DUAL; --12123.23
select to_number('12', '99') from dual; --12
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容