Table name as a PostgreSQL function parameter

前端 未结 8 1890
悲&欢浪女
悲&欢浪女 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:08

    I know this is an old thread, but I ran across it recently when trying to solve the same problem - in my case, for some fairly complex scripts.

    Turning the entire script into dynamic SQL is not ideal. It's tedious and error-prone work, and you lose the ability to parameterize: parameters must be interpolated into constants in the SQL, with bad consequences for performance and security.

    Here's a simple trick that lets you keep the SQL intact if you only need to select from your table - use dynamic SQL to create a temporary view:

    CREATE OR REPLACE FUNCTION some_f(_tbl varchar) returns integer
    AS $$
    BEGIN
        drop view if exists myview;
        execute format('create temporary view myview as select * from %s', _tbl);
        -- now you can reference myview in the SQL
        IF EXISTS (select * from myview where myview.id=1) THEN
         return 1;
        END IF;
        return 0;
    END;
    $$ language plpgsql;
    

提交回复
热议问题