0

This is my query that basically takes two numbers that adds them and multiplies the sum by 10

DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
RETURN ROUND((a+b)*10/9);
END $$
DELIMITER ;

everything is working fine , but I was wondering if there was a way I could add an IF ELSE that checks if any of of the values entered is null and if so the null value is assigned a value of zero

I've tried this but I'm getting an error

DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
IF (a = "") then
a=0;
ELSE IF (b = "")
b=0;
ELSE
END IF;
RETURN ROUND((a+b)*10/9);
END $$
DELIMITER ;
4
  • NULL is not the same thing as an empty string. Commented Sep 10, 2020 at 21:21
  • ELSE IF should only be used when the conditions are mutually exclusive. What if both a and b are null? Commented Sep 10, 2020 at 21:22
  • Why do you think ELSE a=a; is necessary? Why would you need to assign a variable to itself. Commented Sep 10, 2020 at 21:23
  • I just put the a=a by mistake but I've edited it out and for the both b=" "and a='' " I had not thought of that but GMB has provide a perfect solution with coalesce() Commented Sep 10, 2020 at 21:30

1 Answer 1

2

I was wondering if there was a way I could add an IF ELSE that checks if any of of the values entered is null and if so the null value is assigned a value of zero

You can just use coalesce() to assign a default to null parameters:

DELIMITER $$
CREATE FUNCTION tot(a int(4),b INT(4)) RETURNS INT(4)
BEGIN
    RETURN ROUND((COALESCE(a, 0) + COALESCE(b, 0)) * 10 / 9);
END $$
DELIMITER ;
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.