在可以调用的 SQL Server 存储过程中,最简单的类型是不包含任何参数并且返回单个结果集的存储过程。可以使用 Microsoft SQL Server JDBC 驱动程序提供的 SQLServerStatement 类,调用此类存储过程并处理其返回的数据。

使用 JDBC 驱动程序调用不带参数的存储过程时,必须使用 call SQL 转义序列。不带参数的 call 转义序列的语法如下所示:

{call procedure-name}

注意: 有关 SQL 转义序列的详细信息,请参阅使用 SQL 转义序列

作为实例,在 SQL Server 2005 AdventureWorks 示例数据库中创建以下存储过程:

CREATE PROCEDURE GetContactFormalNames 
AS
BEGIN
   SELECT TOP 10 Title + ' ' + FirstName + ' ' + LastName AS FormalName 
   FROM Person.Contact
END

此存储过程返回单个结果集,其中包含一列数据(由 Person.Contact 表中前十个联系人的称呼、名称和姓氏组成)。

在下面的实例中,将向此函数传递 AdventureWorks 示例数据库的打开连接,然后使用 executeQuery 方法调用 GetContactFormalNames 存储过程。

public static void executeSprocNoParams(Connection con) {
   try {
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}");

      while (rs.next()) {
         System.out.println(rs.getString("FormalName"));
      }
      rs.close();
      stmt.close();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}

请参阅

使用带有存储过程的语句