During data migrations it’s common to have constraints disabled, usually for loading performance or testing purposes.
To aid in such task, we’re sharing two simple scripts, one for disabling and another for enabling.
To disable all enabled constraints and triggers, just execute:
BEGIN
-- Constraints
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
ORDER BY c.constraint_type DESC)
LOOP
-- DISABLE
execute immediate 'alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name;
END LOOP;
-- Triggers
FOR ut IN
(select ut.table_owner, ut.trigger_name
from user_triggers ut
where ut.status = 'ENABLED')
LOOP
-- DISABLE
execute immediate 'ALTER TRIGGER "' || ut.table_owner || '"."' || ut.trigger_name || '" DISABLE;';
END LOOP;
END;
/
-- Constraints
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
ORDER BY c.constraint_type DESC)
LOOP
-- DISABLE
execute immediate 'alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name;
END LOOP;
-- Triggers
FOR ut IN
(select ut.table_owner, ut.trigger_name
from user_triggers ut
where ut.status = 'ENABLED')
LOOP
-- DISABLE
execute immediate 'ALTER TRIGGER "' || ut.table_owner || '"."' || ut.trigger_name || '" DISABLE;';
END LOOP;
END;
/
To enable all disabled constraints and triggers, just execute:
BEGIN
-- Constraints
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLE'
ORDER BY c.constraint_type DESC)
LOOP
-- ENABLE
execute immediate 'alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name;
END LOOP;
-- Triggers
FOR ut IN
(select ut.table_owner, ut.trigger_name
from user_triggers ut
where ut.status = 'DISABLE')
LOOP
-- ENABLE
execute immediate 'ALTER TRIGGER "' || ut.table_owner || '"."' || ut.trigger_name || '" ENABLE;';
END LOOP;
END;
/
-- Constraints
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLE'
ORDER BY c.constraint_type DESC)
LOOP
-- ENABLE
execute immediate 'alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name;
END LOOP;
-- Triggers
FOR ut IN
(select ut.table_owner, ut.trigger_name
from user_triggers ut
where ut.status = 'DISABLE')
LOOP
-- ENABLE
execute immediate 'ALTER TRIGGER "' || ut.table_owner || '"."' || ut.trigger_name || '" ENABLE;';
END LOOP;
END;
/