I have a Stored Procedure that runs on MS SQL Server. It takes one parameter as input. Basically, it returns multiple rows. I am calling the SP from my java application by using CallableStatement .
I would like to know if it possible to get the rows returned by the stored procedure in the form of ResultSet in my DAO layer?[like how we get a resultset when we do select * from EmployeeTable ] . If yes, how do we do that?
PS: I don't have privilege to modify the stored procedure.
SQL Server knows two types of procedures returning results:
The procedure looks something like this:
CREATE PROCEDURE p_results(
@p_result_sets INT
)
AS
BEGIN
IF @p_result_sets = 1 BEGIN
SELECT 1 a;
END
ELSE IF @p_result_sets = 2 BEGIN
SELECT 1 a;
SELECT 1 b UNION SELECT 2 b;
END
END;
In this case, you don't know in advance what the result sets will look like, and how many of them you'll get. You will have to run the procedure using Statement.execute()
as follows:
try (CallableStatement stmt = con.prepareCall("...")) {
boolean results = stmt.execute();
for (;;) {
if (results)
try (ResultSet rs = stmt.getResultSet()) {
// ... Fetch your results here
}
else if (stmt.getUpdateCount() != -1) {}
else
break;
results = stmt.getMoreResults();
}
// After all results are fetched, you can also retrieve OUT parameters, if applicable
}
The function looks something like this:
CREATE FUNCTION f_tables1 ()
RETURNS @out_table TABLE (
column_value INTEGER
)
AS
BEGIN
INSERT @out_table
VALUES (1)
RETURN
END
In this case, you don't really need a CallableStatement
. An ordinary SELECT
statement will do:
try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM f_tables1()");
ResultSet rs = stmt.executeQuery()) {
// ... Fetch your results here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.