首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Postgresql Alter Column以幂等方式

Postgresql Alter Column以幂等方式
EN

Stack Overflow用户
提问于 2021-10-13 20:05:23
回答 1查看 97关注 0票数 0

我正在编写一个数据库脚本,其中包含下面这行简单的代码

代码语言:javascript
复制
ALTER TABLE my_table
    ALTER COLUMN my_column TYPE varchar(50);

我怎样才能使这个幂等呢?我似乎不知道是否应该添加ON CONFLICTIF EXISTS子句,以便在后续运行时不会出错。非常感谢您的帮助!

EN

Stack Overflow用户

发布于 2021-10-13 21:28:30

你可以查看information_schema.columns。演示脚本:

代码语言:javascript
复制
drop table if exists my_table;

create table my_table (my_column int);

-- vvvvv alter column idempotently vvvvv
do $$
begin
    
if not exists (
    select 1
    from information_schema."columns"
    where table_name               = 'my_table'
      and column_name              = 'my_column'
      and data_type                = 'character varying'
      and character_maximum_length = 50)
then
    alter table my_table alter column my_column type varchar(50);
    raise notice 'altered the column definition';
else
    raise notice 'data type is already correct';
end if;

end $$;
-- ^^^^^ alter column idempotently ^^^^^

-- Run that same block of code again...
do $$
begin
    
if not exists (
    select 1
    from information_schema."columns"
    where table_name               = 'my_table'
      and column_name              = 'my_column'
      and data_type                = 'character varying'
      and character_maximum_length = 50)
then
    alter table my_table alter column my_column type varchar(50);
    raise notice 'altered the column definition';
else
    raise notice 'data type is already correct';
end if;

end $$;

结果是:

代码语言:javascript
复制
altered the column definition
data type is already correct
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69561702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档