How to replicate IF NOT EXISTS in redshift

0

I am trying to replicate a functionality from SQL Server into redshift where I have to ignore column if the column exists, otherwise add it into the table.

I have come across these posts in stackoverflow, however couldn't find a proper solution from them:

  1. https://stackoverflow.com/questions/65103448/redshift-alter-table-if-not-exists

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

  3. https://stackoverflow.com/questions/42669237/workaround-in-redshift-for-add-column-if-not-exists

I am able to get a TRUE or FALSE for columns that I want to check. But I don't know how to ALTER the table to add or remove one. I am also a bit new to redshift, so I would appreciate a response!

These are some of my attempts:

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();

A few more failed attempts:

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'

Thank you for your time.

질문됨 2년 전4611회 조회
1개 답변
1
수락된 답변

Below I have given a stored procedure that accepts parameters and will perform the column addition if column does not exist.

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');

Hope this helps!

profile pictureAWS
답변함 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠