如何在红移中复制 IF NOT EXISTS

How to replicate IF NOT EXISTS in redshift

我正在尝试将功能从 SQL 服务器复制到 redshift 中,如果该列存在,我必须忽略该列,否则将其添加到 table.

我看过这些帖子,但无法从中找到合适的解决方案:

  1. Redshift Alter table if not exists
  2. Workaround in Redshift for "ADD COLUMN IF NOT EXISTS"

我可以为要检查的列获取 TRUEFALSE。但是我不知道如何ALTER table 添加或删除一个。

这些是我的一些尝试:

IF (SELECT EXISTS(SELECT * FROM pg_catalog.pg_table_def
    WHERE schemaname = 'my_schema'
     AND tablename = 'my_table'
     AND "column" = 'my_new_column'
)) <> TRUE
THEN
   ALTER TABLE my_table
   ADD COLUMN my_new_column varchar
END IF;
CREATE OR REPLACE PROCEDURE if_else()
LANGUAGE plpgsql
AS $$
BEGIN
IF (SELECT EXISTS(SELECT * FROM pg_catalog.pg_table_def
    WHERE schemaname = 'my_schema'
     AND tablename = 'my_table'
     AND "column" = 'my_new_column'
)) <> TRUE
THEN
   ALTER TABLE my_table
   ADD COLUMN my_new_column varchar
END IF;
END;
$$
;

CALL if_else();

还有几次失败的尝试:

CREATE OR REPLACE PROCEDURE alter_my_table()
AS $$
BEGIN
   ALTER TABLE my_table
   ADD COLUMN my_new_column varchar
END;
$$
LANGUAGE plpgsql
;

SELECT 
   CASE WHEN COUNT(*) THEN 'warning: column exists already.'
   ELSE CALL alter_my_table();
   END
FROM pg_catalog.pg_table_def
     WHERE schemaname = 'my_schema'
     AND tablename = 'my_table'
     AND "column" = 'my_new_column'

感谢您的宝贵时间。

我做过这样的事情,效果还不错。

CREATE OR REPLACE PROCEDURE add_table_column(s_name varchar, t_name varchar, c_name varchar, c_type varchar)
LANGUAGE plpgsql
AS $$
BEGIN
IF (SELECT count(1) FROM pg_catalog.pg_table_def
    WHERE schemaname = s_name
     AND tablename = t_name
     AND "column" = c_name
) = 0
THEN
   execute 'ALTER TABLE '||s_name||'.'||t_name||' ADD COLUMN '||c_name||' '||c_type;
END IF;
END;
$$
;

create table public.tst (col1 numeric);

call add_table_column('public','tst','col2','numeric');