I am new to MYSQL and just learning how to create stored procedures.
I am failing to correctly deal with a NULL value using either IF statement or error handling. Any guidance appreciated.
How can I get this code to execute this result if user enters year and month like this
call EmployeeYearMonth(1986,2)
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1
AND MONTH(hire_date) = Num2;
and this result if user only enters year like this
call EmployeeYearMonth(1986)
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1
I have been asked to create a procedure which is able to filter a database according to Year / Month employee was hired. The procedure should be able to work if the user omits the month.
EXAMPLE 1 - I've tried to handle it with an 'IF IS NULL THEN'
but when I run call EmployeeYearMonth(1986);
I get error 1318
DELIMITER $$
CREATE PROCEDURE EmployeeYearMonth(Num1 INT,Num2 INT)
DETERMINISTIC
BEGIN
IF Num2 IS NULL THEN
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1;
ELSE
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1
AND MONTH(hire_date) = Num2;
END IF;
END$$
DELIMITER ;
EXAMPLE 2 -
I've tried to handle the 1318 error
DELIMITER $$
CREATE PROCEDURE EmployeeYearMonth(Num1 INT, Num2 INT)
BEGIN
-- error code for handling missing parameter in event of missing month
DECLARE EXIT HANDLER FOR 1318
BEGIN
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1;
END;
-- main code to handle finding year and month
SELECT * FROM employees
WHERE YEAR(hire_date) = Num1
AND MONTH(hire_date) = Num2;
END$$
DELIMITER ;