我正在编写一个数据库脚本,其中包含下面这行简单的代码
ALTER TABLE my_table
ALTER COLUMN my_column TYPE varchar(50);我怎样才能使这个幂等呢?我似乎不知道是否应该添加ON CONFLICT或IF EXISTS子句,以便在后续运行时不会出错。非常感谢您的帮助!
发布于 2021-10-13 21:28:30
你可以查看information_schema.columns。演示脚本:
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 $$;结果是:
altered the column definition
data type is already correcthttps://stackoverflow.com/questions/69561702
复制相似问题