如果在 Postgresql 中不存在则添加列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21848128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:19:23  来源:igfitidea点击:

Add Column If Not Exists in Postgresql

postgresqlpostgresql-9.3

提问by postgreat

Is postgresql (9.3.2) can do check the existence of a column before add a new column? I don't want to create a function just for to check the existence.

postgresql ( 9.3.2) 是否可以在添加新列之前检查列是否存在?我不想创建一个函数只是为了检查是否存在。

Just simply like this :

就像这样:

  ALTER TABLE IF NOT EXISTS table_name ADD COLUMN column_name data_type;

回答by Thalis K.

You'll need to write your own stored procedure in Plpgsql to check if the table has this column. For this you'll need the tables PG_ATTRIBUTE and PG_CLASS where Postgres stores the schema metadata and in particular the information about columns and tables respectively.

您需要在 Plpgsql 中编写自己的存储过程来检查表是否具有此列。为此,您将需要表 PG_ATTRIBUTE 和 PG_CLASS,其中 Postgres 分别存储架构元数据,特别是有关列和表的信息。

The query whose result you need to check in your stored procedure would be a JOIN like:

您需要在存储过程中检查其结果的查询将是一个 JOIN,如:

SELECT A.ATTNAME FROM PG_ATTRIBUTE A, PG_CLASS C                                             
WHERE A.ATTRELID = C.OID AND A.ATTNAME = 'column_name_check_if_exists' AND C.relname= 'table_name' ;

回答by jokie1982

In DDL, you can only:

在 DDL 中,您只能:

  • Add columns
  • Remove columns
  • Add constraints
  • Remove constraints
  • Change default values
  • Change column data types
  • Rename columns
  • Rename tables
  • 添加列
  • 删除列
  • 添加约束
  • 移除约束
  • 更改默认值
  • 更改列数据类型
  • 重命名列
  • 重命名表

ALTER TABLE: SYNOPSIS AND EXAMPLES -> http://www.postgresql.org/docs/9.3/static/sql-altertable.html

更改表:概要和示例 -> http://www.postgresql.org/docs/9.3/static/sql-altertable.html

For validations... you need make "PL/SQL"

对于验证......你需要制作“PL/SQL”

回答by postgreat

So, there is no such query. I should using PLPGSQL.

所以,没有这样的查询。我应该使用 PLPGSQL。