问题很简单。如何添加列x到表y,但只有当x列不存在?我发现唯一的解决方案在这里如何检查列是否存在。
SELECT column_name
FROM information_schema.columns
WHERE table_name='x' and column_name='y';
问题很简单。如何添加列x到表y,但只有当x列不存在?我发现唯一的解决方案在这里如何检查列是否存在。
SELECT column_name
FROM information_schema.columns
WHERE table_name='x' and column_name='y';
当前回答
对于那些使用Postgre 9.5+的人(我相信你们大多数人都在使用),有一个非常简单和干净的解决方案
ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>
其他回答
下面的选择查询将返回true/false,使用EXISTS()函数。
EXISTS(): EXISTS的参数是一个任意的SELECT语句,或者 子查询。计算子查询以确定它是否返回 任何行。如果它至少返回一行,则EXISTS的结果为 “真正的”;如果子查询不返回任何行,EXISTS的结果为 “假”
SELECT EXISTS(SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'x'
AND column_name = 'y');
并使用下面的动态SQL语句修改表
DO
$$
BEGIN
IF NOT EXISTS (SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'x'
AND column_name = 'y') THEN
ALTER TABLE x ADD COLUMN y int DEFAULT NULL;
ELSE
RAISE NOTICE 'Already exists';
END IF;
END
$$
只需检查查询是否返回了一个column_name。
如果不是,执行如下命令:
ALTER TABLE x ADD COLUMN y int;
你把一些有用的东西放在x和y上,当然还有一个合适的数据类型,我用的是int。
对于那些使用Postgre 9.5+的人(我相信你们大多数人都在使用),有一个非常简单和干净的解决方案
ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>
可以添加到迁移脚本调用函数,并在完成时删除。
create or replace function patch_column() returns void as
$$
begin
if exists (
select * from information_schema.columns
where table_name='my_table'
and column_name='missing_col'
)
then
raise notice 'missing_col already exists';
else
alter table my_table
add column missing_col varchar;
end if;
end;
$$ language plpgsql;
select patch_column();
drop function if exists patch_column();
下面的函数将检查列是否存在,如果返回适当的消息,否则它将把列添加到表中。
create or replace function addcol(schemaname varchar, tablename varchar, colname varchar, coltype varchar)
returns varchar
language 'plpgsql'
as
$$
declare
col_name varchar ;
begin
execute 'select column_name from information_schema.columns where table_schema = ' ||
quote_literal(schemaname)||' and table_name='|| quote_literal(tablename) || ' and column_name= '|| quote_literal(colname)
into col_name ;
raise info ' the val : % ', col_name;
if(col_name is null ) then
col_name := colname;
execute 'alter table ' ||schemaname|| '.'|| tablename || ' add column '|| colname || ' ' || coltype;
else
col_name := colname ||' Already exist';
end if;
return col_name;
end;
$$