上一篇文章讲到了《oracle如何自动分区》,今天主要讲一下,如何更新分区字段值?好了,下面我们直接进去正题。
0.创建自动分区表,按月创建分区表
create table test_part
(
ID NUMBER(20) not null,
REMARK VARCHAR2(1000),
create_time DATE
) tablespace USERS
PARTITION BY RANGE (CREATE_TIME) INTERVAL (numtoyminterval(1, 'month'))
(partition part_t01 values less than(to_date('2020-08-01', 'yyyy-mm-dd')));
初始化数据
--插入数据
insert into test_part(ID,REMARK,create_time) values (4,'44444',to_date('2020-07-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (1,'11111',to_date('2020-08-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (2,'22222',to_date('2020-09-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (3,'22222',to_date('2020-10-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (5,'22222',to_date('2020-11-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (6,'22222',to_date('2020-12-01', 'yyyy-mm-dd'));
insert into test_part(ID,REMARK,create_time) values (7,'22222',to_date('2021-01-01', 'yyyy-mm-dd'));
1.查看表里面的数据
select * from test_part
2.查看分区信息
select * from user_tab_partitions where table_name='TEST_PART';
3.更新id=7的数据 日期改成2021-02-01
update test_partset create_time=to_date('2021-02-01','yyyy-mm-dd') where id=7;
表分区的时候要确定分区字段是否会UPDATE,如果会的话一定要开启行迁移,否则就会报错
如上图,直接弹出一个ora-14402错误,原因是因为 默认情况下,oracle不允许更改分区字段的值。
4.开启行迁移
alter table TEST_PART enable row movement;
再次执行更新语句,这样在update以后,会在老分区删除数据,新分区插入数据。
update test_part set create_time=to_date('2021-02-01','yyyy-mm-dd') where id=7;
执行成功
5.验证更改的信息
select * from test_part
select * from user_tab_partitions where table_name='TEST_PART';
查看结果,说明ID=7的create_time已被更新,并且自动建立了一个新的分区‘SYS_P44’。