通过Postgresql中的名称删除约束

我怎么才能知道名称在Postgresql中删除约束名称? 我有一个由第三方脚本自动生成的约束列表。 我需要删除它们而不知道表名只是约束名。

您需要通过运行以下查询来检索表名称:

SELECT * FROM information_schema.constraint_table_usage WHERE table_name = 'your_table' 

或者,您可以使用pg_constraint来检索这些信息

 select n.nspname as schema_name, t.relname as table_name, c.conname as constraint_name from pg_constraint c join pg_class t on c.conrelid = t.oid join pg_namespace n on t.relnamespace = n.oid where t.relname = 'your_table_name'; 

然后你可以运行所需的ALTER TABLE语句:

 ALTER TABLE your_table DROP CONSTRAINT constraint_name; 

当然,你可以让查询返回完整的alter语句:

 SELECT 'ALTER TABLE '||table_name||' DROP CONSTRAINT '||constraint_name||';' FROM information_schema.constraint_table_usage WHERE table_name in ('your_table', 'other_table') 

如果有多个具有相同表的模式,请不要忘记在WHERE子句(和ALTER语句)中包含table_schema。

如果你在9.x的PG上,你可以使用DO语句来运行它。 只要做一下a_horse_with_no_name做的事情,但是将它应用到DO声明中。

 DO $$DECLARE r record; BEGIN FOR r IN SELECT table_name,constraint_name FROM information_schema.constraint_table_usage WHERE table_name IN ('your_table', 'other_table') LOOP EXECUTE 'ALTER TABLE ' || quote_ident(r.table_name)|| ' DROP CONSTRAINT '|| quote_ident(r.constraint_name) || ';'; END LOOP; END$$;