移動表到指定表空間的動態sql

不少時候,咱們想把一個表空間的數據移動到另外一個表空間去,若是隻是一張表,那比較簡單,但若是有不少張表,數據比較大,好比有幾t,那麼,這時使用單純的一條條手工命令,可能容易出現問題,畢竟移動表空間,這裏涉及到索引的建立,lobsegment,lobindex的類型的移動,這些都一條條去輸入,容易出錯,下面我寫了一個腳本,使用動態 sql來完成這個操做:
好比要把users表空間的數據移動到ts_exchange表空間去,那麼就修改前兩行便可,反之,調換一下便可。

set serveroutput on
define tsname='USERS'
define totsname ='TS_EXCHANGE'
declare
strtabsql varchar2(200);
stridxsql varchar2(200);
strlobsegsql varchar2(200);
strlobidxsql varchar2(200);

begin

for c_tabresult in (select owner,segment_name,bytes/1024/1024,segment_type 
from dba_segments
where tablespace_name='&tsname'
and segment_type ='TABLE'
order by 3 desc) loop
strtabsql:= 'ALTER table ' || c_tabresult.owner || '.' || c_tabresult.segment_name || ' move tablespace &totsname';
dbms_output.put_line(strtabsql);
execute immediate strtabsql;
for c_idxresult in (
select owner,index_name
from dba_indexes
where tablespace_name='&tsname'
and table_name =c_tabresult.segment_name) loop
stridxsql:='alter index ' || c_idxresult.owner || '.' || c_idxresult.index_name || ' rebuildonline tablespace &totsname';
dbms_output.put_line(stridxsql);
execute immediate stridxsql
end loop;

for c_lobsegresult in (
select a.owner,b.table_name,b.column_name,b.SEGMENT_NAME
from dba_segments a,dba_lobs b
where a.segment_name=b.segment_name
and a.tablespace_name='&tsname'
and b.table_name=c_tabresult.segment_name
and a.segment_type='LOBSEGMENT') loop
strlobsegsql:='ALTER TABLE ' || c_lobsegresult.owner || '.' || c_lobsegresult.table_name || ' move tablespace &totsname lob(' || c_lobsegresult.column_name || ') store as ' || c_lobsegresult.SEGMENT_NAME || ' (TABLESPACE &totsname)';
dbms_output.put_line(strlobsegsql);
execute immediate strlobsegsql
END loop;

for c_lobidxresult in (
select a.owner,b.table_name,b.column_name,b.SEGMENT_NAME
from dba_segments a,dba_lobs b
where a.segment_name=b.segment_name
and a.tablespace_name='&tsname'
and b.table_name=c_tabresult.segment_name
and a.segment_type='LOBINDEX') loop
strlobidxsql:='ALTER TABLE ' || c_lobidxresult.owner || '.' || c_lobidxresult.table_name || ' move tablespace &totsname lob(' || c_lobidxresult.column_name || ') store as ' || c_lobidxresult.SEGMENT_NAME || ' (TABLESPACE &totsname)';
dbms_output.put_line(strlobidxsql);
execute immediate strlobidxsql
END loop;

end loop;
end;
/
undefine tsname
undefine totsname

這種方式的最大好處,就是一張張表移動,對於受影響的面,可控。sql

相關文章
相關標籤/搜索