Oracle 刪除用戶和表空間

Oracle 使用時間長了, 新增了許多user 和tablespace. 須要清理一下sql

對於單個user和tablespace 來講, 能夠使用以下命令來完成。
ide

 步驟一:  刪除user
oop

drop user ×× cascade

說明: 刪除了user,只是刪除了該user下的schema objects,是不會刪除相應的tablespace的。
fetch

步驟二: 刪除tablespacespa

DROP TABLESPACE tablespace_name INCLUDING CONTENTS AND DATAFILES;



可是,由於是供開發環境來使用的db, 須要清理的user 和 table space 不少。code

思路ip

 Export出DB中全部的user和tablespace, 篩選出系統的和有用的tablespace,把有用的信息load到一張表中去。開發

而後寫例程循環,把不在有用表的tablespace刪掉it

1.pip

select username,default_tablespace from dba_users;

2. 

create table MTUSEFULSPACE
 (
    ID Number(4) NOT NULL PRIMARY KEY,
    USERNAME varchar2(30),
    TABLESPACENAME varchar2(60),
    OWNERNAME varchar2(30)
 );

3.

declare icount number(2);
         tempspace varchar2(60);
 begin
   for curTable in (select username as allusr,default_tablespace as alltblspace from dba_users)
   loop
   tempspace :=curTable.alltblspace;
   dbms_output.put_line(tempspace);
   select count(TABLESPACENAME) into icount from MTUSEFULSPACE where TABLESPACENAME = tempspace;
   if icount=0 then
     DROP TABLESPACE tempspace INCLUDING CONTENTS AND DATAFILES;
   end if;
   commit;
   end loop;
 end;


執行後會報以下錯誤

ORA-06550: 第 10 行, 第 5 列:
PLS-00103: 出現符號 "DROP"在須要下列之一時:
 begin case declare exit
   for goto if loop mod null pragma raise return select update
   while with <an identifier>
   <a double-quoted delimited-identifier> <a bind variable> <<
   close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:


好像是被鎖了。。


沒辦法,例程不能寫,就只能組出語句執行了。

把須要刪除的user, tablespace 導出到Excel. 使用CONCATENATE 組出SQL.

貼到SQLdevelop 批量執行。


整個刪除會比較耗時間, 100多個user.  用了12個小時左右。


如要找datafile的具體位置,能夠使用

select t1.name,t2.name from v$tablespace t1, v$datafile t2 where t1.ts# = t2.ts#;


SQL code
--刪除空的表空間,可是不包含物理文件

drop tablespace tablespace_name;

--刪除非空表空間,可是不包含物理文件

drop tablespace tablespace_name including contents;

--刪除空表空間,包含物理文件

drop tablespace tablespace_name including datafiles;

--刪除非空表空間,包含物理文件

drop tablespace tablespace_name including contents and datafiles;

--若是其餘表空間中的表有外鍵等約束關聯到了本表空間中的表的字段,就要加上CASCADE CONSTRAINTS

drop tablespace tablespace_name including contents and datafiles CASCADE CONSTRAINTS;
相關文章
相關標籤/搜索