1

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.

1
  • Sequence does not support rollback Commented Feb 1, 2013 at 10:02

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.