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
The
IF @vgloc = NULL THENdoes not work as you expect because you can’t checkNULLwith equality (=).NULLis a special value that is not equal to anything, not even to itself.To check for NULL value, you need:
IF @vgloc IS NULL THEN.But you can also use
COALESCE()function for further simplicity: