1. 程式人生 > >Oracle 兩張表名交換

Oracle 兩張表名交換

CREATE OR REPLACE PROCEDURE P_SWICH_OBJECT(PI_FROM VARCHAR2,
                                               PI_TO   VARCHAR2) IS
  TMP_SWITCH_NAME VARCHAR2(255);
BEGIN
  --對兩個物件加排他鎖
  EXECUTE IMMEDIATE 'lock table ' || PI_FROM || ' in exclusive mode';
  EXECUTE IMMEDIATE 'lock table ' || PI_TO || ' in exclusive mode';

  --生成臨時表名,應確保該名錶不存在
  TMP_SWITCH_NAME := 'tmpsw_' || SUBSTR(PI_FROM, 1, 20);
  EXECUTE IMMEDIATE 'alter table ' || PI_TO || ' rename to ' ||
                    TMP_SWITCH_NAME;
  EXECUTE IMMEDIATE 'alter table ' || PI_FROM || ' rename to ' || PI_TO;
  EXECUTE IMMEDIATE 'alter table ' || TMP_SWITCH_NAME || ' rename to ' ||
                    PI_FROM;

  --釋放排他鎖
  COMMIT;
END;

使用:

CALL P_SWICH_OBJECT(T_TEMP1,T_TEMP)