Skip to content

Generated keys no longer returned if there is a trigger on insert #2740

@OS-veracardoso

Description

@OS-veracardoso

Driver version

13.2.0.jre11

SQL Server version

Microsoft SQL Server 2019 (RTM-CU21) (KB5025808) - 15.0.4316.3 (X64)
Jun 1 2023 16:32:31
Copyright (C) 2019 Microsoft Corporation
Express Edition (64-bit) on Windows Server 2016 Datacenter 10.0 (Build 14393: ) (Hypervisor)

Client Operating System

  • macOS Sequoia 15.6
  • Ubuntu 24.04.2 LTS


.

JAVA/JVM version

21.0.7

Table schema

DDL:

CREATE TABLE TABLE_A (ID int NOT NULL IDENTITY(1,1) PRIMARY KEY, NAME varchar(32));
CREATE TABLE TABLE_B (ID int NOT NULL IDENTITY(1,1) PRIMARY KEY);
CREATE TRIGGER INSERT_ON_TABLE_B ON TABLE_A FOR INSERT AS INSERT INTO TABLE_B DEFAULT VALUES;

Problem description

There is a table (TABLE_A) with an auto-generated primary key and a trigger on insert that inserts a single row in another table (TABLE_B).

When inserting a single row in table TABLE_A it would be to expect the new generated key to be returned, however, an exception is thrown when calling getResultSet: com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained..

Code snipet:

            String sql =  "INSERT INTO TABLE_A (NAME) VALUES (?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql, new String[]{"ID"});
            preparedStatement.setString(1, "test");
            boolean execute = preparedStatement.execute();
            ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
            int updateCount = preparedStatement.getUpdateCount();

Expected behavior

When executing a single insert in TABLE_A the generated primary key is returned (🔴).
The update count is returned as 1 (✅ ).

Actual behavior

The update count is returned as 1, as expected, but the generated primary key is not returned.

Error message/stack trace

com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained.
	at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:250)
	at com.microsoft.sqlserver.jdbc.SQLServerStatement.getGeneratedKeys(SQLServerStatement.java:2394)

Any other details that can be helpful

  • When using driver version 13.1.1.jre11-preview, this works as expected.
  • If we remove the trigger, it works as expected.

JDBC trace logs

Provide the JDBC driver trace logs. Instructions can be found here: https://docs.microsoft.com/sql/connect/jdbc/tracing-driver-operation

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions