0

I have this SQL function:

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

How do I execute this function in java and what data type do I even bind it to?

This is what I came up with and it works but it seems like I'm coloring outside the lines here:

PreparedStatement ps = con.prepareStatement("SELECT dbo.Average(" + year + ")");
ResultSet rs = ps.executeQuery();
rs.next();
System.out.println("Average: " + rs.getFloat(""));
2
  • This works depending on the database engine. For example, this won't work on oracle. Commented Sep 20, 2013 at 23:34
  • I believe this syntax is for MS products only. Commented Sep 21, 2013 at 1:40

1 Answer 1

1

Use CallableStatement as below: 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(){ ....}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.