如何使用后期绑定查询序列的 last_value
How to query last_value of a sequence using late-binding
是否可以从变量中存储名称的序列中获取最后一个值?
seq_name := 'myschema.mysequence';
SELECT last_value FROM ${seq_name};
如果该序列已经在会话中使用,您可以简单地使用 currval
函数:
DO
$$DECLARE
var text := 'seq';
BEGIN
RAISE NOTICE 'The current value is %', currval(var);
END;$$;
NOTICE: The next value is 1
否则需要动态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
是否可以从变量中存储名称的序列中获取最后一个值?
seq_name := 'myschema.mysequence';
SELECT last_value FROM ${seq_name};
如果该序列已经在会话中使用,您可以简单地使用 currval
函数:
DO
$$DECLARE
var text := 'seq';
BEGIN
RAISE NOTICE 'The current value is %', currval(var);
END;$$;
NOTICE: The next value is 1
否则需要动态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