Table name as a PostgreSQL function parameter

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

    If you want table name, column name and value to be dynamically passed to function as parameter

    use this code

    create or replace function total_rows(tbl_name text, column_name text, value int)
    returns integer as $total$
    declare
    total integer;
    begin
        EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;
        return total;
    end;
    $total$ language plpgsql;
    
    
    postgres=# select total_rows('tbl_name','column_name',2); --2 is the value
    

提交回复
热议问题