在Postgresql中按名称删除约束

dan*_*car 74 postgresql

如何通过知道名称在Postgresql中删除约束名称?我有一个由第三方脚本自动生成的约束列表.我需要删除它们而不知道表名只是约束名.

a_h*_*ame 123

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

SELECT *
FROM information_schema.constraint_table_usage
WHERE table_name = 'your_table'
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用它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';
Run Code Online (Sandbox Code Playgroud)

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

ALTER TABLE your_table DROP CONSTRAINT constraint_name;
Run Code Online (Sandbox Code Playgroud)

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

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

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


Kub*_*aun 13

如果您在PG的9.x上,您可以使用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$$;
Run Code Online (Sandbox Code Playgroud)


Pra*_*r C 5

-- 删除正确的外键约束

ALTER TABLE affiliations
DROP CONSTRAINT affiliations_organization_id_fkey;
Run Code Online (Sandbox Code Playgroud)

笔记:

隶属关系 -> 表名

affiliations_organization_id_fkey -> 约束名称