0

I used this mysql function to retrieve the sum of a column's data with passing three parameters. Function return the sum of whole column regardless of where clause. I mean that the query inside the function act as it has no where clause and this query works fine when used without function. Here is the function

DELIMITER $$
CREATE FUNCTION calculate_customer_loan(customer_id INT, currency VARCHAR(10), type VARCHAR(10)) RETURNS DOUBLE
BEGIN
 DECLARE total DOUBLE;
 SELECT SUM(`amount`) INTO total FROM `deals` WHERE `customer_id` = customer_id AND `currency` = currency AND `type` = type;
 RETURN total;
END
$$
DELIMITER ;

Any idea! help me.

asked Feb 23, 2017 at 11:36
1
  • Rename your function parameters. Commented Feb 23, 2017 at 11:40

1 Answer 1

2

You have a problem with parameter names matching column names. The column names win.

So, name your parameters to avoid ambiguity:

DELIMITER $$
CREATE FUNCTION calculate_customer_loan (
 in_customer_id INT,
 in_currency VARCHAR(10),
 in_type VARCHAR(10)
) RETURNS DOUBLE
BEGIN
 DECLARE v_total DOUBLE;
 SELECT SUM(d.amount) INTO v_total
 FROM deals d
 WHERE d.customer_id = in_customer_id AND
 d.currency = in_currency AND
 d.type = in_type;
 RETURN v_total;
END
$$
DELIMITER ; 

I removed the backticks. They are not needed and -- more importantly -- they do not distinguish between column names and variable names.

answered Feb 23, 2017 at 11:41
Sign up to request clarification or add additional context in comments.

4 Comments

"The column names win" - I wouldn't say so: stackoverflow.com/questions/715229/…
@PaulSpiegel . . . That answer would appear to be incorrect.
That answer seams to be correct. Here is a simple test: rextester.com/JEWVL30269 However I would still use different names.
@GordonLinoff Isn't there a typo in this answer. You never actually set v_total.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.