一、cast函數(shù)
成都創(chuàng)新互聯(lián)是一家專注于成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),和田網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十多年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:和田等地區(qū)。和田做網(wǎng)站價(jià)格咨詢:18982081108
cast函數(shù)的作用是對(duì)用戶輸入的數(shù)據(jù)進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換,比如用戶數(shù)據(jù)的數(shù)據(jù)時(shí)number類型,小數(shù)位數(shù)是3位,我們可以將用戶數(shù)據(jù)轉(zhuǎn)換成×××數(shù)據(jù)int類型。
cast函數(shù)的格式是cast(數(shù)據(jù)源 as 待轉(zhuǎn)換的數(shù)據(jù)類型)
比如我需要將number數(shù)據(jù)類型的13.658轉(zhuǎn)換成int類型的整數(shù)類型
SQL> select cast(13.658 as int) from dual;
CAST(13.658ASINT)
---------------------------------------
14
通過(guò)上圖我們可以看見(jiàn),cast對(duì)number數(shù)據(jù)類型的數(shù)據(jù)進(jìn)行四舍五入操作后保存成×××數(shù)據(jù);
上面的效果類似于round函數(shù)。
但是cast函數(shù)作用的結(jié)果并不作用于數(shù)據(jù)庫(kù)表結(jié)構(gòu),僅僅用戶數(shù)據(jù)顯示。舉例如下:
--info表的數(shù)據(jù)記錄如下:
SQL> select * from info;
SNO SNAME
--------------------------------------- --------------------
1 lilei
2 dushuai
3 caolirong
--info表字段結(jié)構(gòu)
desc info
Name Type Nullable Default Comments
----- ------------ -------- ------- --------
SNO INTEGER
SNAME VARCHAR2(20) Y
--我們使用cast函數(shù)對(duì)sno字段進(jìn)行數(shù)據(jù)類型轉(zhuǎn)換,轉(zhuǎn)換成number(8,4)
SQL> select cast(sno as number(8,4)) from info;
CAST(SNOASNUMBER(8,4))
----------------------
1.0000
2.0000
3.0000
--但是重新查找info表,結(jié)果如下
SQL> select * from info;
SNO SNAME
--------------------------------------- --------------------
1 lilei
2 dushuai
3 caolirong
--使用update函數(shù)進(jìn)行info表更新
SQL> update info set sno=cast(sno as number(3,2)) where sno=1;
1 row updated
SQL> commit;
--重新查找info表,結(jié)果如下
SQL> select * from info;
SNO SNAME
--------------------------------------- --------------------
1 lilei
2 dushuai
3 caolirong
如果想利用cast函數(shù)實(shí)現(xiàn)數(shù)據(jù)類型的轉(zhuǎn)換,可以考慮在基表的基礎(chǔ)上創(chuàng)建視圖或者新建另外一張表的方式。下例為在基表的基礎(chǔ)上創(chuàng)建視圖進(jìn)而實(shí)現(xiàn)改變數(shù)據(jù)類型的目的:
SQL> create or replace view v_info as select cast(sno as number(3,2)) as v_sno from info;
View created
SQL> select * from v_info;
V_SNO
-----
1.00
2.00
3.00
SQL> desc v_info;
Name Type Nullable Default Comments
----- ----------- -------- ------- --------
V_SNO NUMBER(3,2) Y
SQL> desc info
Name Type Nullable Default Comments
----- ------------ -------- ------- --------
SNO INTEGER
SNAME VARCHAR2(20) Y