0

我有这个 SQL 函数:

CREATE FUNCTION Average (@year int)
RETURNS decimal(4,2)
AS
BEGIN
    DECLARE @result as decimal(4,2);
    SET @result = (SELECT AVG(CAST(MilkQuantity AS decimal(4,2))) FROM MilkProduction WHERE YEAR(Date) = @year);
    RETURN @result;
END
GO

我如何在 java 中执行这个函数,我什至将它绑定到什么数据类型?

这是我想出的,它有效,但似乎我在这里的线条之外着色:

PreparedStatement ps = con.prepareStatement("SELECT dbo.Average(" + year + ")");
ResultSet rs = ps.executeQuery();
rs.next();
System.out.println("Average: " + rs.getFloat(""));
4

1 回答 1

1

使用 CallableStatement 如下: CallableStatement stmt = null; String sql = "begin ? := Average(?); end;"; ResultSet rs = null; try { stmt = conn.prepareCall(sql); stmt.registerOutParameter(1, INT); stmt.setString(2, "VALUE"); stmt.execute(); } Catch(){ ....}

于 2015-12-11T10:13:56.533 回答