Created
June 27, 2018 14:52
-
-
Save jromero/bab7e5413c764c553d11027d3bb31cdf to your computer and use it in GitHub Desktop.
Enable / Disable Foreign Key Constraints in Oracle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE | |
/* The name of the schema that should be synchronized. */ | |
SCHEMA_NAME_ VARCHAR2(4000) := 'YOUR_SCHEMA'; | |
/* The operation type: */ | |
/* ON — enable foreign keys. */ | |
/* OFF — disable foreign keys. */ | |
OPERATION_ VARCHAR2(4000) := 'OFF'; | |
PROCEDURE CONSTRAINTS_ON_OFF(TARGET_SCHEMA_ IN VARCHAR2, ACTION_ IN VARCHAR2 := '') | |
IS | |
SQL_STRING_ VARCHAR2(4000); | |
FK_NAME_ VARCHAR2(4000); | |
NEW_STATE_ VARCHAR2(4000); | |
CURSOR CURSOR_ IS | |
SELECT | |
'ALTER TABLE ' || OWNER || '.' || | |
TABLE_NAME || ' ' || NEW_STATE_ || ' CONSTRAINT ' || CONSTRAINT_NAME AS sql_string, | |
CONSTRAINT_NAME | |
FROM | |
ALL_CONSTRAINTS | |
WHERE | |
CONSTRAINT_TYPE = 'R' AND OWNER = TARGET_SCHEMA_ | |
ORDER BY CONSTRAINT_NAME ASC; | |
BEGIN | |
IF UPPER(ACTION_) = 'ON' | |
THEN | |
NEW_STATE_ := 'ENABLE'; | |
ELSE | |
NEW_STATE_ := 'DISABLE'; | |
END IF; | |
OPEN CURSOR_; | |
LOOP | |
FETCH CURSOR_ INTO SQL_STRING_, FK_NAME_; | |
EXIT WHEN CURSOR_%NOTFOUND; | |
EXECUTE IMMEDIATE SQL_STRING_; | |
DBMS_Output.PUT_LINE('Foreign key ' || FK_NAME_ || ' has been ' || NEW_STATE_ || 'D'); | |
END LOOP; | |
EXCEPTION | |
WHEN OTHERS | |
THEN | |
BEGIN | |
DBMS_Output.PUT_LINE(SQLERRM); | |
END; | |
CLOSE CURSOR_; | |
END; | |
BEGIN | |
CONSTRAINTS_ON_OFF(SCHEMA_NAME_, OPERATION_); | |
END; | |
/ | |
COMMIT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight alteration of: https://blog.devart.com/how-to-disable-all-foreign-keys-in-oracle-scheme.html