Reputation: 679
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
Upvotes: 0
Views: 5680
Reputation: 115530
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;
Upvotes: 4