Para soltar y recrear dinámicamente una restricción de clave externa, puede envolverlo todo en una función o usar el DO
comando:
DO
$body$
DECLARE
_con text := (
SELECT quote_ident(conname)
FROM pg_constraint
WHERE conrelid = 'myschema.mytable'::regclass
AND confrelid = 'myschema.myreftable'::regclass
LIMIT 1 -- there could be multiple fk constraints. Deal with it ...
);
BEGIN
EXECUTE '
ALTER TABLE wuchtel12.bet DROP CONSTRAINT ' || _con;
-- do stuff here
EXECUTE '
ALTER TABLE myschema.mytable
ADD CONSTRAINT ' || _con || ' FOREIGN KEY (col)
REFERENCES myschema.myreftable (col)';
END
$body$
Debe poseer la tabla para usar ALTER TABLE
.
Si no, puede crear una función con LANGUAGE plpgsql SECURITY DEFINER
(usando el mismo cuerpo) y
ALTER FUNCTION foo() OWNER TO postgres;
postgres
ser un superusuario aquí, o el propietario de la tabla.
Pero asegúrese de saber lo que dice el manual sobre seguridad.
El manual también tiene más información sobre comandos dinámicos.