Redshift: add column if not exists

試著忘記壹切 提交于 2019-12-23 10:54:39

问题


The following works in Postgres 9.6 but not in Redshift:

ALTER TABLE stats
    ADD COLUMN IF NOT EXISTS panel_exit timestamp;

Can the same functionality be achieved in Redshift?


回答1:


There is no Amazon Redshift command equivalent to ADD COLUMN IF NOT EXISTS.

See: ALTER TABLE documentation

To replicate this functionality, your application would first need to query the table metadata and then make the decision whether to issue the ADD COLUMN command.




回答2:


John's answer set me in the right direction, here is the command I found best worked in Redshift to check for a column's existence.

SELECT EXISTS(
    SELECT * FROM pg_table_def
    WHERE schemaname = '<my_schema_name>'
    and tablename = '<my_table_name>'
    and "column" = '<my_column_name>'
);

Note the double quotes around "column" are required since column is also a keyword.

Additionally, if the table you are interested in is not in the public schema. You may need to first modify your search path so the results are returned as expected:

set SEARCH_PATH to <schema_name>;

See the PG_TABLE_DEF AWS Docs for more details.



来源:https://stackoverflow.com/questions/42035068/redshift-add-column-if-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!