使用不含参数的存储过程

下载 JDBC 驱动程序

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

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

{call procedure-name}

注意

若要详细了解 SQL 转义序列,请参阅使用 SQL 转义序列

作为示例,在 AdventureWorks2022 示例数据库中创建以下存储过程:

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

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

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

public static void executeSprocNoParams(Connection con) throws SQLException {  
    try(Statement stmt = con.createStatement();) {  

        ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}");  
        while (rs.next()) {  
            System.out.println(rs.getString("FormalName"));  
        }  
    }  
}

另请参阅

结合使用语句和存储过程