如果列存在于 PostgreSQL 9+ 中,如何删除它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40472673/
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
How to drop column if it exists in PostgreSQL 9+?
提问by user3521432
I am trying to drop a column from a table. How can I check if the column exists or not?
我正在尝试从表中删除一列。如何检查该列是否存在?
I went through the documentation at https://www.postgresql.org/docs/9.2/static/sql-altertable.html, but didn't find any example how to do it.
我浏览了https://www.postgresql.org/docs/9.2/static/sql-altertable.html 上的文档,但没有找到任何示例。
Even found How to check if a column exists in a SQL Server table?, but it does not seem relevant.
甚至发现如何检查 SQL Server 表中是否存在列?,但似乎并不相关。
回答by user3521432
You just need to add IF EXIST
to your DROP COLUMN
statement:
你只需要IF EXIST
在你的DROP COLUMN
声明中添加:
ALTER TABLE tableName
DROP COLUMN IF EXISTS columnName;
回答by Piyush Sharma
You can also try via IF EXISTS Method which work great while we are using migration
您也可以尝试通过 IF EXISTS 方法,该方法在我们使用迁移时效果很好
DO $$
BEGIN
IF EXISTS(
SELECT column_name FROM information_schema.columns WHERE table_name = tableName AND column_name = columnName)
THEN
ALTER TABLE tableName DROP COLUMN columnName;
END IF;
END $$;