Let's say there is a sequence created on SQL Server:
CREATE SEQUENCE dbo.my_seq
START WITH 1
INCREMENT BY 1
NO CYCLE;
GO
And the following Java code to fetch the next sequence value:
Connection conn = ...;
String sql = "SELECT NEXT VALUE FOR my_seq;";
try (Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
long seq = resultSet.getLong(1);
System.out.println(seq);
}
}
Why are sequences jumping by two when this code is executed repeatedly?
2
4
6
I've tried with the CACHE option on and off. It makes no difference.
Sequences are incremented by one if I execute the same query multiple times on Azure Data Studio.
I'm running Microsoft SQL Server 2019 (RTM-CU15) (KB5008996) - 15.0.4198.2 (X64). I tried the same code with com.microsoft.sqlserver:mssql-jdbc:10.2.0.jre8 and com.microsoft.sqlserver:mssql-jdbc:11.1.1.jre8-preview drivers and got the same behavior.
I analyzed the SQL Server query history, and the Java code made only one query to fetch the next sequence value per execution.