您的位置:首页 > 数据库 > Oracle

oracle 数据库之数字处理

2015-12-02 15:56 465 查看

1、修改表名

代码:

--大写为系统命令
ALTER TABLE old_table_name RENAME TO new_table_name


2、数字处理

oracle sql 对数字进行操作:

取上取整

取上取整

向下取整

保留N位小数

四舍五入

数字格式化

2.1 向上取整

select ceil(5.534) from dual;


2.2 向下取整

select floor(5.534) from dual;
select trunc(5.534) from dual;


2.3 四舍五入

SELECT round(5.534) FROM dual;
SELECT round(5.534,0) FROM dual;
SELECT round(5.534,1) FROM dual;
SELECT round(5.534,2) FROM dual;


2.4 保留N位小数(不四舍五入)

select trunc(5.534,0) from dual;
select trunc(5.534,1) from dual;
select trunc(5.534,2) from dual;


2.5 数字格式化:

select to_char(12345.123,'99999999.9999') from dual;
select to_char(12345.123,'99999999.9900') from dual;
select to_char(0.123,'99999999.9900') from dual;
select to_char(0.123,'99999990.9900') from dual;


3、 复制表结构

1、复制表结构及其数据:

create table table_name_new as select * from table_name_old 2.


2、只复制表结构:

create table table_name_new as select * from table_name_old where 1=2;


create table table_name_new like table_name_old;


3、只复制表数据:

如果两个表结构一样:

insert into table_name_new select * from table_name_old;


如果两个表结构不一样:

insert into table_name_new(column1,column2...)
select column1,column2... from table_name_old;


4、 更新数据

参考:Oracle中用一个表的数据更新另一个表的数据

Oracle 中用一个表的数据更新另一个表的数据

有下面两个表:将表tab1中id值与和表tab2中id值相同的行的val更新为tab2中val的值.

错误代码:

update tab1 set val=(select val from tab2 where tab1.id=tab2.id);


更新完后的结果是:
(select * from tab1)
,在tab1中有的行,如果在tab2中没有对应的行,值被更新为null


正确的代码:

update tab1 set val=(select val from tab2 where tab1.id=tab2.id)
where exists (select 1 from tab2 where tab1.id=tab2.id)


仍存在的问题:

但是如果tab2中有多条对应tab1中一条的情况也会出错。

最好的方法是用merge语法:

merge into tab1
using tab2
on(tab1.id=tab2.id)
when matched then
update set tab1.val = tab2.val


同样,如果tab2中有多条对应tab1中一条的情况也会出错:

(ORA-30926:unable to get a stable set of rows in the source tables )


可以通过在using中的subquery中将重复记录过滤来避免这种错误,merge终极版:

merge into tab1
using  (select * FROM tab2 X  WHERE  X.ROWID =
(SELECT MAX(Y.ROWID) FROM  tab2 Y  WHERE  X.ID = Y.ID)) tab2
on(tab1.id=tab2.id)
when matched then
update set tab1.val = tab2.val
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: