简体   繁体   English

Postgres函数返回数字0-7循环吗?

[英]Postgres function returning the number 0-7 round robin?

How can I write a function which returns for example the numbers 0-7 round robin, in a "thread safe" manner ensuring a new number for each call (wrap around if > 7)? 如何编写以“线程安全”的方式返回例如0-7循环数字的函数,以确保每个调用都有新的数字(如果> 7,则换行)?

It should be a global function so if "connection 1" calls it and gets the number 3, "connection 2" should get the number 4 when it calls and so on. 它应该是全局函数,因此,如果“连接1”调用它并获得数字3,则“连接2”调用时应获得数字4,依此类推。

as per docs , you can cycle sequence: 根据docs ,您可以循环序列:

t=# create sequence rr07 minvalue 0 maxvalue 7 cycle;
CREATE SEQUENCE
t=# select nextval('rr07');
 nextval
---------
       0
(1 row)

t=# select nextval('rr07');
 nextval
---------
       1
(1 row)

t=# select nextval('rr07');
 nextval
---------
       2
(1 row)

t=# select nextval('rr07');
 nextval
---------
       3
(1 row)

t=# select nextval('rr07');
 nextval
---------
       4
(1 row)

t=# select nextval('rr07');
 nextval
---------
       5
(1 row)

t=# select nextval('rr07');
 nextval
---------
       6
(1 row)

t=# select nextval('rr07');
 nextval
---------
       7
(1 row)

t=# select nextval('rr07');
 nextval
---------
       0
(1 row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM