2017-10-09 28 views
2

sys_sequences上没有next_value列,所以您需要获取current_value并增加它。如何知道序列的下一个值而不增加它?

select convert(int, current_value) + 1 as next_value 
from sys.sequences 
where name = 'my_sequence' 

重新启动序列时出现问题,以前的查询将返回错误的值。

alter sequence my_sequence restart with 100; 

select convert(int, current_value) + 1 as next_value 
from sys.sequences 
where name = 'my_sequence' 

这将返回101而不是真正的未来价值,这是100

你知道的一种可靠的方法来计算一个序列的下一个值?

+3

为什么在使用之前你需要知道下一个值会是什么?如果你对它有这么多的依赖,那么无论如何我都会对代码中的竞争条件保持警惕。 –

+2

你可以通过检查'sys.sequences'目录视图来知道序列的**当前**值,但是你永远无法可靠地知道将要发布的**下一个值** - 你必须调用' SELECT ... NEXT VALUE FOR ...'为了实际得到下一个值 - 没有提前“偷看” –

+0

@SeanLange我使用序列生成账单号码,并且我想通知用户最后一个值/下一个值按计费顺序。但是在SQL Server上,我无法知道current_value实际上是最后一个值还是将在该序列上使用的下一个值。 –

回答

1

您是否知道计算序列的下一个值的可靠方法?

据我所知,你是正确的。一种可能的解决方法是将您的重新启动值设置为比您想要的还要少,并在您的restart之后用虚拟变量用完第一个值。

create sequence my_sequence as int start with 1; 
alter sequence my_sequence restart with 99; 
declare @dummy int = next value for my_sequence; 

select convert(int, s.current_value) + convert(int,s.increment) as next_value 
from sys.sequences s 
where s.name = 'my_sequence'; 

dbfiddle.uk

但作为marc_s指出,没有可靠的 “窥视”,为下一个值。

+0

我喜欢这个解决方法,很简单。我要这样设定,谢谢。 –

+0

@MarcGuillot乐意帮忙! – SqlZim

相关问题