Search code examples
functionpostgresqlselectprimary-keyexecute

Create a function using execute (plpgsql)


I want to make a function that returns the next value of a primary key based on the table name:

CREATE OR REPLACE FUNCTION next_pk (_table varchar) RETURNS INTEGER AS $$
    BEGIN
        RETURN EXECUTE 'SELECT COALESCE (MAX (primary_key), 0) + 1 FROM ' || quote_ident (_table) || ' limit 1';
    END;
$$ LANGUAGE plpgsql;

select next_pk ('myTable');

But it gives the following error:

ERROR:  type "execute" does not exist
LINE 1: SELECT EXECUTE 'SELECT COALESCE (MAX (primary_key), 0) + 1 F...

Any clues ? Thanks.


Solution

  • You need integer variable and 'execute into':

    CREATE OR REPLACE FUNCTION next_pk (_table varchar) RETURNS INTEGER AS $$
    DECLARE
        result integer;    
    BEGIN  
        EXECUTE 
            'SELECT COALESCE (MAX (primary_key), 0) + 1 FROM ' || quote_ident (_table) 
            INTO result;
        RETURN result;
    END;
    $$ LANGUAGE plpgsql;
    
    select next_pk ('myTable');