1、ORACLE資料庫中的外鍵約束名都在表user_constraints中可以查到。其中constraint_type='R'表示是外鍵約束。
2、啟用外鍵約束的命令為:alter table table_name enable constraint constraint_name
3、禁用外鍵約束的命令為:alter table table_name disable constraint constraint_name
4、然後再用SQL查出資料庫中所以外鍵的約束名:
select 'alter table '||table_name||' enable constraint '||constraint_name||';' from user_constraints where constraint_type='R'
select 'alter table '||table_name||' disable constraint '||constraint_name||';' from user_constraints where constraint_type='R'
ORACLE 禁用/啟用外鍵和觸發器
在很多資料庫維護工作中,經常會遇到對現有資料的匯入匯出的操作,但是資料庫中表與表之間有很多外間關係,不能直接的按維護要求對資料進行操作,所有需要對這些外鍵和觸發器臨時的禁用,然後在操作資料,完成操作後在啟用對應的外鍵和觸發器,下面的指令碼就是提供對整個使用者物件的外鍵和觸發器的禁用和啟用指令碼:
--禁用指令碼
SET SERVEROUTPUT ON SIZE 100000
BEGIN
for c in (select 'ALTER TABLE '||TABLE_NAME||' DISABLE CONSTRAINT '||constraint_name||' ' as v_sql from user_constraints where CONSTRAINT_TYPE='R') loop
DBMS_OUTPUT.PUT_LINE(C.V_SQL);
begin
EXECUTE IMMEDIATE c.v_sql;
exception when others then
dbms_output.put_line(sqlerrm);
end;
end loop;
for c in (select 'ALTER TABLE '||TNAME||' DISABLE ALL TRIGGERS ' AS v_sql from tab where tabtype='TABLE') loop
dbms_output.put_line(c.v_sql);
begin
execute immediate c.v_sql;
exception when others then
dbms_output.put_line(sqlerrm);
end;
end loop;
end;
/
--啟用指令碼
SET SERVEROUTPUT ON SIZE 100000
BEGIN
for c in (select 'ALTER TABLE '||TABLE_NAME||' ENABLE CONSTRAINT '||constraint_name||' ' as v_sql from user_constraints where CONSTRAINT_TYPE='R') loop
DBMS_OUTPUT.PUT_LINE(C.V_SQL);
begin
EXECUTE IMMEDIATE c.v_sql;
exception when others then
dbms_output.put_line(sqlerrm);
end;
end loop;
for c in (select 'ALTER TABLE '||TNAME||' ENABLE ALL TRIGGERS ' AS v_sql from tab where tabtype='TABLE') loop
dbms_output.put_line(c.v_sql);
begin
execute immediate c.v_sql;
exception when others then
dbms_output.put_line(sqlerrm);
end;
end loop;
end;
/