Bases de datos

Oracle

Eliminación y creación de llaves foráneas

La unión de estos dos SELECTs da como resultado el listado de comandos de eliminación y creación de todas las llaves foráneas que existan en la base de datos a la que se está conectado.

IMPORTANTE:
Este comando no es útil al 100% si existen llaves foráneas a tablas cuya llave primaria esté compuesta de más de una columna.

 
SELECT XSQL
FROM (
    SELECT 10 AS N, 'alter table ' || TABLE_NAME || ' drop constraint ' || CONSTRAINT_NAME || ';' AS XSQL
    FROM all_constraints WHERE owner = USER AND CONSTRAINT_TYPE = 'R' AND NOT TABLE_NAME LIKE '%$%'
    UNION
    SELECT
    20, 'alter table '
            || a.TABLE_NAME
            || ' ADD CONSTRAINT ' || a.CONSTRAINT_NAME
            || ' FOREIGN KEY (' || b.COLUMN_NAME || ')'
            || ' REFERENCES ' || c.TABLE_NAME || ' (' || d.COLUMN_NAME || ');'
    FROM all_constraints a
        inner join ALL_CONS_COLUMNS b ON a.owner = USER AND b.owner = USER AND a.CONSTRAINT_TYPE = 'R' AND NOT a.TABLE_NAME LIKE '%$%' AND b.constraint_name = a.constraint_name
        inner join all_constraints c ON c.owner = USER AND c.CONSTRAINT_NAME = a.R_CONSTRAINT_NAME
        inner join ALL_CONS_COLUMNS d ON d.owner = USER AND d.constraint_name = c.constraint_name
)  x
ORDER BY x.N;