SQL Server-从序列中获取下一个值,而不推进当前值



我正试图编写一个存储过程,验证序列中的NEXT VALUE是否等于表中的最大值加1。我通过将表编号与sys.sequences.中序列的current_value进行比较来实现这一点

然而,我在这方面遇到了麻烦,因为我不知道如何区分current_value为"1"且NEXT value将为"1"的情况与NEXT VALVE将为"2"的情况。

我不想实际调用NEXT VALUE,因为我不想提前序列的计数。

例如,这种情况:

CREATE SEQUENCE  testseq AS bigint START WITH 1 INCREMENT BY 1 CACHE 500000
select current_value from sys.sequences where name = 'testseq'

其中current_value为1,下一个值将为1

与。

select NEXT VALUE for testseq
select current_value from sys.sequences where name = 'testseq'

其中current_value是1并且下一个值将是2。

我将无法更改序列的属性。有什么想法吗?

适用于SQL Server 2017及更新版本:

SELECT CASE WHEN last_used_value IS NULL
THEN CAST(current_value as bigint)
ELSE CAST(current_value as bigint) + 1
END AS next_val
FROM sys.sequences WHERE name = 'sequence_name'
select cast(current_value as int) + cast(increment as int) from sys.sequences where name = 'testseq'

最新更新