postgresql - PostgreSQL 中选择查询返回的删除约束

标签 postgresql

我正在编写一个迁移脚本来删除在不同环境中具有不同名称的约束

放弃这个约束:

ALTER TABLE ONLY custom_data
    ADD CONSTRAINT fk_rails_d86d725d64
    FOREIGN KEY (custom_id) REFERENCES customs(id);

我想做这样的事情:(但它不起作用)

alter table custom_data
drop constraint (
    SELECT CONSTRAINT_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE TABLE_NAME =  'custom_data'
    AND COLUMN_NAME =  'custom_id')

有没有其他方法可以改写上面的措辞,这样它可能会起作用?或者有人可以帮助我理解为什么上述方法不起作用吗?

更新

还尝试使用 do 但它也不起作用。检查时约束仍然存在。

do $$
    declare c_name text;
    begin
        select constraint_name into c_name
        from information_schema.key_column_usage
        where table_name = 'custom_data' and 
            column_name = 'custom_id';

      execute format ('alter table custom_data drop constraint %I', c_name);
    end;
$$;

如果运行 select 语句,

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME =  'custom_data'
AND COLUMN_NAME =  'custom_id'

有时结果是,

 | constraint_name
_|____________________
1| fk_rails_d86d725d64

但有时结果是,

 | constraint_name
_|____________________
1| 

在运行大查询以获取约束并将其删除时,

有时结果是,

Empty query string

但有时结果是,

Name         | Value
_____________|___________
Query        | do
Updated Rows | 0
Finish time  | Tue Mar 21...

现在对我来说它开始像是一个糟糕的空白问题......

这也会受到已经有索引的列的影响吗?

CREATE INDEX index_custom_data_on_custom_id ON custom_data USING btree (custom_id);

最佳答案

解决方案:

改变:

select constraint_name
from information_schema.key_column_usage
where table_name = 'custom_data' and 
      column_name = 'custom_id';

收件人:

select constraint_name
from information_schema.key_column_usage
where table_name = 'custom_data' and column_name = 'custom_id';

我猜这是一个空白问题。感谢评论中的所有帮助。

关于postgresql - PostgreSQL 中选择查询返回的删除约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915220/

相关文章:

sql - 在触发器函数中,如何获取正在更新的字段

postgresql - Postgres : select the sum of values and then sum this again

sql - Postgres 使用主键索引作为覆盖索引

postgresql - Cloud SQL 时间点数据驻留

python - 使用 Python 获取为 Postgresql SERIAL KEY 插入的最后一条记录的 id

Django 连接到 PostgreSQL : "Peer authentication failed"

arrays - PLPGSQL 数组索引从 1 开始?

sql - Postgres 对 Index 与 Seq Scan 的使用不一致

java - 在JOOQ中实现batchMerge()

sql - postgres查询根据某些列的多个副本获取第一行