how to write to dynamically created table in Redshift procedure

人走茶凉 提交于 2021-01-28 19:12:43

问题


I need to write a procedure in Redshift that will write to a table, but the table name comes from the input string. Then I declare a variable that puts together the table name.

CREATE OR REPLACE PROCEDURE my_schema.data_test(current "varchar")
    LANGUAGE plpgsql
AS $$                                                        
declare new_table varchar(50) = 'new_tab' || '_' || current;

BEGIN 
    select 'somestring' as colname into new_table;
    commit;
END;
$$

This code runs but it doesn't create a new table, no errors. If I remove the declare statement then it works, creating a table called "new_table". It's just not using the declared variable name.

It's hard to find good examples because Redshift is postgresql and all the postgresql pages say that it only has functions, not procedures. But Redshift procedures were introduced last year and I don't see many examples.


回答1:


Well, when you are declaring a variable "new_table", and performing a SELECT ..INTO "new_table", the value is getting assigned to the variable "new_table". You will see that if you return your variable using a OUT parameter.

And when you remove the declaration, it simply work as a SELECT INTO syntax of Redshift SQL and creates a table.

Now to the solution:

Create a table using the CREATE TABLE AS...syntax.

Also you need to pass the value of declared variable, so use the EXECUTE command.

CREATE OR REPLACE PROCEDURE public.ct_tab (vname varchar)
AS $$  
DECLARE tname VARCHAR(50):='public.swap_'||vname;

BEGIN 

execute 'create table ' || tname || ' as select ''name''';

END;
$$ LANGUAGE plpgsql 
;

Now if you call the procedure passing 'abc', a table named "swap_abc" will be created in public schema.

call public.ct_tab('abc');

Let me know if it helps :)



来源:https://stackoverflow.com/questions/60713329/how-to-write-to-dynamically-created-table-in-redshift-procedure

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