【问题标题】:How to drop constraint by name in PostgreSQL?如何在 PostgreSQL 中按名称删除约束?
【发布时间】:2011-03-11 13:49:18
【问题描述】:

如何仅通过知道名称就在 PostgreSQL 中删除约束?

我有一个由第 3 方脚本自动生成的约束列表。我需要在不知道表名的情况下删除它们,只知道约束名。

【问题讨论】:

  • 你用的是什么版本的PG?

标签: postgresql


【解决方案1】:

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

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。

【讨论】:

    【解决方案2】:

    如果您在 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$$;
    

    【讨论】:

      【解决方案3】:

      删除右外键约束

      ALTER TABLE affiliations
      DROP CONSTRAINT affiliations_organization_id_fkey;
      

      注意:

      affiliations -> Table Name
      
      affiliations_organization_id_fkey ->Constraint name
      

      【讨论】:

        猜你喜欢
        • 2012-09-05
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 1970-01-01
        • 2019-11-08
        • 2015-03-27
        • 2011-10-14
        • 2011-02-02
        相关资源
        最近更新 更多