从Java中的存储过程(msql)检索数据

时间:2018-08-23 19:36:23

标签: java sql-server stored-procedures jdbc

我在sql server中有此存储过程:

create procedure [dbo].[prSum]

AS
    create table @SUM (
         ClientName Varchar(40), 
         SearchDoc Varchar(20), 
         SearchName Varchar(20), 
    )
    --each one of this procedures returns a query with the same colunms size of @SUM
    insert into @SUM exec pr1
    insert into @SUM exec pr2
    insert into @SUM exec pr3
    insert into @SUM exec pr4
    insert into @SUM exec pr5

RETURN Select * from @SUM
GO

在SSMS中,我可以运行:

exec prSum 

并显示@SUM中的Select *。

但是我尝试使用jdbc在我的Java类上获取它:

package calc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectURL {
    public static void main(String[] args) {

        String connectionUrl = "jdbc:sqlserver://######;databaseName=####;user=#####;password=###;

        try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();) {
            String SQL = "{ call dbo.prSum}";
            ResultSet rs = stmt.executeQuery(SQL);

            while (rs.next()) {
                System.out.println(rs.getString("ClientName"));
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

获取并获取此信息:

com.microsoft.sqlserver.jdbc.SQLServerException:该语句未返回结果集。

1 个答案:

答案 0 :(得分:1)

您的存储过程有很多问题。但是实际上 不会返回任何数据。您正在返回,然后再将结果发送给客户端。

应该是这样的:

create procedure [dbo].[prSum]

AS
begin
    set nocount on;
    declare @SUM table (
         ClientName Varchar(40), 
         SearchDoc Varchar(20), 
         SearchName Varchar(20)
    )
    --each one of this procedures returns a query with the same colunms size of @SUM
    insert into @SUM exec pr1;
    insert into @SUM exec pr2;
    insert into @SUM exec pr3;
    insert into @SUM exec pr4;
    insert into @SUM exec pr5;

    Select * from @SUM;
    return;
end
GO