martes, 13 de agosto de 2013

DROP AND ADD FOREING KEY IN POSTGRESQL

SELECT
        'ALTER TABLE ' || tc.table_name || ' DROP CONSTRAINT ' || tc.constraint_name || ';' AS eliminar_foranea,
        'ALTER TABLE ' || tc.table_name || ' ADD CONSTRAINT ' || tc.constraint_name || ' FOREIGN KEY '
        || '(' || kcu.column_name || ') REFERENCES ' || ccu.table_name || '(' || kcu.column_name
        || ') MATCH SIMPLE ON UPDATE ' || rc.update_rule || ' ON DELETE ' || rc.delete_rule
        || CASE WHEN tc.is_deferrable = 'YES' THEN ' DEFERRABLE' END
        || CASE WHEN tc.initially_deferred = 'YES' THEN ' INITIALLY DEFERRED;' END AS agregar_foranea
    FROM information_schema.table_constraints tc
        JOIN information_schema.constraint_column_usage ccu
        ON tc.constraint_catalog = ccu.constraint_catalog
        AND tc.constraint_schema = ccu.constraint_schema
        AND tc.constraint_name = ccu.constraint_name

        JOIN information_schema.key_column_usage kcu
        ON tc.constraint_catalog = kcu.constraint_catalog
        AND tc.constraint_schema = kcu.constraint_schema
        AND tc.constraint_name = kcu.constraint_name

        JOIN information_schema.referential_constraints rc
        ON tc.constraint_catalog = rc.constraint_catalog
        AND tc.constraint_schema = rc.constraint_schema
        AND tc.constraint_name = rc.constraint_name
    WHERE lower(tc.constraint_type) in ('foreign key')
        AND ccu.table_name in (tablaSQL);

No hay comentarios:

Publicar un comentario