3

I have trigger function:

CREATE OR REPLACE FUNCTION update_aaa() RETURNS TRIGGER AS $$
DECLARE maxid INTEGER;
BEGIN
    SELECT MAX(id) INTO maxid FROM aaa;
    ALTER SEQUENCE aaa_id_seq RESTART WITH maxid;
END;
$$ LANGUAGE plpgsql;

And have error:

ERROR:  syntax error at or near "$1"
Line 1: ALTER SEQUENCE aaa_id_seq RESTART WITH  $1 

Why $1 ?
What error?

0

3 Answers 3

5

Maybe use the setval function rather than alter sequence ... restart with?

SELECT pg_catalog.setval('aaa_id_seq'::regclass, maxid, false);
Sign up to request clarification or add additional context in comments.

1 Comment

You usually need that to be PERFORM, and that last false needs to go, otherwise you have an off-by-one error.
0

I think you need to use EXECUTE for data definition commands (like ALTER) in PL/pgSQL. And you need to LOCK TABLE aaa IN SHARE MODE; before calculating MAX(id) to prevent concurrent changes to table data.

2 Comments

Hmm... if I wrote: CREATE OR REPLACE FUNCTION update_aaa() RETURNS TRIGGER AS $$ DECLARE maxid INTEGER; BEGIN SELECT MAX(id) INTO maxid FROM aaa; ALTER SEQUENCE aaa_id_seq RESTART WITH 999; END; $$ LANGUAGE plpgsql; All good...
Because you did not use any variable in your statement and PL/pgSQL parser was not confused. Maybe I should write "dynamic data definition commands".
0

Your table is probably empty so

SELECT MAX(id) INTO maxid FROM aaa;

returns NULL;

Change the query to

SELECT COALESCE(MAX(id), <some_appropriate_value>) INTO maxid FROM aaa;

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.