在Java中执行用户定义的SQL Server功能

时间:2013-09-20 23:27:22

标签: java sql sql-server

我有这个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(""));

1 个答案:

答案 0 :(得分: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(){ ....}