Is it possible to obtain the last value from a sequence of which name is stored in a variable?
seq_name := 'myschema.mysequence';
SELECT last_value FROM ${seq_name};
CodePudding user response:
If the sequence has already been used in the session, you can simply user the currval function:
DO
$$DECLARE
var text := 'seq';
BEGIN
RAISE NOTICE 'The current value is %', currval(var);
END;$$;
NOTICE: The next value is 1
Otherwise, you need dynamic SQL:
DO
$$DECLARE
var text := 'seq';
value bigint;
BEGIN
EXECUTE format('SELECT last_value FROM %s', var) INTO value;
RAISE NOTICE 'The current value is %', value;
END;$$;
NOTICE: The current value is 1
