有些項目中可能會涉及到表的分區(有的表大小在70G左右) 下面簡單寫一下建立分區表過程
1、建立測試表
首先建立測試表weihai_test語句如下
create table weihai_test (
id int notnull,
join_date DATE);
以上表中join_date字段為分區表字段
2、插入資料
2.1、模拟插入30萬條資料
plsql/developer 工具執行
declare
i int := 1;
year VARCHAR2(20);
begin
loop
year :=CASE mod(i, 3)
WHEN 0 THEN
'2015-12-01 00:00:00'
WHEN 1 THEN
'2016-12-01 00:00:00'
ELSE
'2017-12-01 00:00:00'
END;
insert into weihai_test values(i, to_date(year, 'yyyy-mm-dd hh24:mi:ss'));
exit when i= 300000;
i := i+ 1;
end loop;
end;
commit;
2.2、檢視是否插入成功
select count(1) from weihai_test;
3、重命名原表,生成臨時表
資料插入完成後,重命名原表,這裡示範的是停機之後的操作,如果是線上操作,建議使用oracle 線上重定義功能來保障資料不丢失
rename weihai_test to weihai_test_his; (這個過程隻建議應用停機的時候做)
4、建立分區表
create table weihai_test (
id int notnull,
join_date DATE )
partition by range(join_date)
(
partition weihai_test_2016_less values less than (to_date('2016-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) tablespace fmt,
partition weihai_test_2016 values less than (to_date('2017-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) tablespace fmt,
partition weihai_test_2017 values less than (to_date('2018-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')) tablespace fmt,
partition weihai_test_max values less than (to_date('2999-12-31 23:59:59','yyyy-mm-ddhh24:mi:ss')) tablespace fmt
);
5、資料轉移
表建立完成之後,開始導數,
insert into weihai_test (
id,
join_date) select
id,
join_date from weihai_test_his;
commit;
6、資料對比
導入完成之後,對比兩張表的資料,一樣就表示導入成功
select count(1) from weihai_test_his;
select count(1) from weihai_test;
7、檢視執行計劃
查詢資料,檢視執行計劃,與臨時表weihai_test_his相比較,是否掃描的更少
explain plan for select * from weihai_test_his where join_date <= date'2016-01-01';
select plan_table_output from table(dbms_xplan.display());
同樣的查詢在分區表執行一遍
explain plan for select * from weihai_test where join_date <= date'2016-01-01';
select plan_table_output from table(dbms_xplan.display());
相比之下,分區表耗費的資源更少
8、删除臨時表
資料導入完成之後,drop臨時表
drop table weihai_test_his;