Oracle使用遊標刪除所有使用者資料表中的所有記錄指令碼
應用情境:因為Oracle資料庫中的資料涉及機密資訊,希望一次效能刪除掉所有資料,只保留資料表結構,供新項目開發程式用
測試結果:經查詢已刪除所有資料
存在問題:資料表如果存在外鍵的話下面指令碼可能執行不成功,請自行刪除或者過濾掉該表,見
操作辦法:直接將下面的指令碼內容複寫到PQSQL中執行即可
--Oracle使用遊標刪除所有使用者資料表中的所有記錄指令碼
declare mystring NVARCHAR2(1000):=''; --定義要輸出的字串變數
cursor mycursor is --定義遊標
select * from user_tables order by table_name; --查詢所有使用者表
myrecord mycursor%rowtype; --定義遊標記錄類型
Counter int :=0;
begin
open mycursor; --開啟遊標
if mycursor%isopen then --判斷開啟成功
loop --迴圈擷取記錄集
fetch mycursor into myrecord; --擷取遊標中的記錄
if mycursor%found then --遊標的found屬性判斷是否有記錄
begin
mystring:='truncate from '||myrecord.table_name;
dbms_output.put_line('當前動作陳述式為'||mystring);
if(myrecord.table_name<>'TABLE_INFO') then
execute immediate 'truncate table '||myrecord.table_name;
end if;
commit;--立即執行
end;
else
exit;
end if;
end loop;
else
dbms_output.put_line('遊標沒有開啟');
end if;
close mycursor;
end;