Table name as a PostgreSQL function parameter

前端 未结 8 1888
悲&欢浪女
悲&欢浪女 2020-11-21 05:37

I want to pass a table name as a parameter in a Postgres function. I tried this code:

CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS inte         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 06:07

    I have 9.4 version of PostgreSQL and I always use this code:

    CREATE FUNCTION add_new_table(text) RETURNS void AS
    $BODY$
    begin
        execute
            'CREATE TABLE ' || $1 || '(
            item_1      type,
            item_2      type
            )';
    end;
    $BODY$
    LANGUAGE plpgsql
    

    And then:

    SELECT add_new_table('my_table_name');
    

    It works good for me.

    Attention! Above example is one of those which shows "How do not if we want to keep safety during querying the database" :P

提交回复
热议问题