0

im having problems creating a function that must return the amount of goals of a team as a home and away First it sums all local goals, and then it sums all visitor goals, and saves into variables, but the problem is, i want to know what can i do if there is NO data, i mean, what can i do when it returns NULL, i tried with IF ELSE but still not working, here is the code:

CREATE DEFINER=`root`@`localhost` FUNCTION `vgoles`(`veq` int) RETURNS int(11)
BEGIN
#Routine body goes here...
DECLARE vgloc INT;
DECLARE vgvis INT;
DECLARE vgoles INT;
SELECT SUM(gloc) INTO @vgloc FROM partidos WHERE eqloc=@veq;
SELECT SUM(gvis) INTO @vgvis FROM partidos WHERE eqvis=@veq;
IF @vgloc = NULL THEN
SET @vgloc = 0;
END IF;
IF @vgvis = NULL THEN
SET @vgvis = 0;
END IF;
SET @vgoles=@vgloc+@vgvis;
RETURN @vgoles;
END

Thanks and have a nice day

1 Answer 1

4

The IF @vgloc = NULL THEN does not work as you expect because you can't check NULL with equality (=). NULL is a special value that is not equal to anything, not even to itself.

SELECT (3 = NULL)          --yields--> NULL
SELECT NOT (3 = NULL)      --yields--> NULL
SELECT (NULL = NULL)       --yields--> NULL
SELECT (NULL <> NULL)      --yields--> NULL
SELECT (NULL IS NULL)      --yields--> TRUE  

To check for NULL value, you need: IF @vgloc IS NULL THEN.

But you can also use COALESCE() function for further simplicity:

SELECT COALESCE(SUM(gloc),0) INTO @vgloc FROM partidos WHERE eqloc=@veq;
SELECT COALESCE(SUM(gvis),0) INTO @vgvis FROM partidos WHERE eqvis=@veq;
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thanks so much! PD: Since is a function, i cant put an '@' on the parameter variable, that was the other problem, but now it works very good!

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.