I have an SQL Server stored procedure similar to this:
CREATE PROCEDURE proc1
(
@param DECIMAL
)
AS
BEGIN
INSERT INTO table1 (@param);
-- further commands
END;
GO
This procedure is called from Java. I introduced a unique constraint on table1
, on the same column which is inserted above. Is expected to get an SQLException in Java in case of a constraint violation, but it is not happening. When the procedure is executed manually from SSMS, I can see that it prints the constraint violation error, and then continues along the rest of the process, which I think is weird, I expected it to fail. So I changed it like this:
CREATE PROCEDURE proc1
(
@param DECIMAL
)
AS
BEGIN
BEGIN TRY
INSERT INTO table1 (@param);
END TRY
BEGIN CATCH
THROW 51000, 'Unable to insert', 1;
END CATCH
-- further commands
END;
GO
Now when I execute it manually in SSMS, the procedure stops in case of a failure, and prints my error message. However the Java calling process is not receiving any indication of the error. How can I propagate this error to the Java calling layer?
UPDATE: Java calling layer:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://x.x.x.x;database=x";
try (Connection conn = DriverManager.getConnection(connectionUrl, "x", "x")) {
try (CallableStatement stmt = conn.prepareCall("{call proc1(?)}")) {
stmt.setInt(1, 1);
stmt.execute();
System.out.println("Done");
}
}
At the end, I can see the "Done" message printed to the console.
Add SET NOCOUNT ON
as the first statement in the proc to suppress the DONE_IN_PROC
(rowcount) TDS messages. Otherwise, the code will need to consume all results returned using a ResultSet
and getMoreResults
before the error is raised on the client.