Table name as a PostgreSQL function parameter

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

    The first doesn't actually "work" in the sense that you mean, it works only in so far as it does not generate an error.

    Try SELECT * FROM quote_ident('table_that_does_not_exist');, and you will see why your function returns 1: the select is returning a table with one column (named quote_ident) with one row (the variable $1 or in this particular case table_that_does_not_exist).

    What you want to do will require dynamic SQL, which is actually the place that the quote_* functions are meant to be used.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题