I have the following table:
create table cumpleanios(
Id_cumpleanios pk ai,
Id_user mediumint,
cumpleanios varchar(12)
);
What I want to do is compare the field cumpleanios
to know if a user has already inserted the birthday for the following year, and if not, insert it.
Id_cumpleanios Id_user Cumpleanios
1 5 14/09/2017
2 7 28/03/2017
3 8 08/10/2017
4 9 03/07/2017
5 7 28/03/2018
I started a stored procedure and my idea is to send it to call from an event that runs every year (I'll do this also for other tables).
DROP PROCEDURE IF EXISTS InsertCumpleanios;
DELIMITER $$
CREATE PROCEDURE InsertCumpleanios(IN anioLast varchar(15))
BEGIN
-- Variables donde almacenar lo que nos traemos desde el SELECT
DECLARE p_iduser TINYINT;
DECLARE p_anio varchar(5);
DECLARE p_mes varchar(3);
DECLARE p_dia varchar(3);
DECLARE anioAct varchar(5);
DECLARE p_total TINYINT;
-- Variable para controlar el fin del bucle
DECLARE fin TINYINT DEFAULT 0;
-- El SELECT que vamos a ejecutar
DECLARE cumple_cursor CURSOR FOR
SELECT u.Id_user, DAY(c.cumpleanios), MONTH(c.cumpleanios), YEAR(c.cumpleanios)
FROM cumpleanios c INNER JOIN usuarios u ON u.Id_user = c.Id_user WHERE u.Estado = 'Disponible' ORDER BY YEAR(c.cumpleanios) ASC;
-- Condición de salida
DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin=1;
OPEN cumple_cursor;
get_cumple: loop
FETCH cumple_cursor INTO p_iduser, p_dia, p_mes, p_anio;
IF fin=1 then
LEAVE get_orden;
END IF;
SELECT p_iduser, p_dia, p_mes, p_anio; -- almacena fila de datos actual
-- SELECT count(DISTINCT campo) FROM tabla
SET p_total = (SELECT COUNT(DISTINCT p_iduser));
SELECT YEAR(CURDATE()) as anioActual; -- Obtiene el año actual
SELECT u.Id_user, DAY(c.cumpleanios), MONTH(c.cumpleanios), YEAR(c.cumpleanios)
FROM cumpleanios c INNER JOIN usuarios u ON u.Id_user = c.Id_user
WHERE u.Estado = 'Disponible' ORDER BY YEAR(c.cumpleanios) ASC LIMIT p_total;
IF p_anio < anioActual
INSERT INTO cumpleanios(Id_user, cumpleanios) VALUES(p_iduser, CONCAT(p_anio, '-', p_mes, '-', p_dia));
END LOOP get_cumple;
CLOSE cumple_cursor;
END $$ DELIMITER ;