Table name as a PostgreSQL function parameter

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

    Inside plpgsql code, The EXECUTE statement must be used for queries in which table names or columns come from variables. Also the IF EXISTS () construct is not allowed when query is dynamically generated.

    Here's your function with both problems fixed:

    CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer 
    AS $$
    DECLARE
     v int;
    BEGIN
          EXECUTE 'select 1 FROM ' || quote_ident(param) || ' WHERE '
                || quote_ident(param) || '.id = 1' INTO v;
          IF v THEN return 1; ELSE return 0; END IF;
    END;
    $$ LANGUAGE plpgsql;
    

提交回复
热议问题