I am new to procedures and I am trying to implement them within my customer website.
I want to create a procedure to add a new customer. I want to check to make sure there phoneNumber is not already in the database. If it is, I want to display an error message. If the phone number is not in the db, I want to insert it into my CUSTOMER table.
I have implemented the following but I am getting an error. I am not sure if I am declaring variables right in MySQL, and I am not sure if the “if statement” is valid in the way I have done it. Also, how could I set the if statement query to a variable? If anyone could help, it would mean a lot. Thanks!
DELIMITER //
CREATE PROCEDURE add_Customer
(IN customerNum int,
IN last varchar,
IN first varchar)
BEGIN
DECLARE output var DEFAULT '';
IF SELECT CUSTOMER.customerNum FROM CUSTOMER WHERE CUSTOMER.customerNum= customerNum
THEN
SET output= "Customer already exists!";
select output;
ELSE
INSERT INTO CUSTOMER VALUES (customerNum, last, first);
END IF;
END//
DELIMITER;
EDITED
DELIMITER //
CREATE PROCEDURE add_Customer
(IN customerNum int,
IN last varchar,
IN first varchar)
BEGIN
DECLARE output var DEFAULT '';
DECLARE var_num INT;
SELECT CUSTOMER.customerNum INTO var_num FROM CUSTOMER WHERE CUSTOMER.customerNum= customerNum
if var_num IS NULL THEN
INSERT INTO CUSTOMER VALUES (customerNum, last, first);
ELSE
SET output= "Customer already exists!";
select output;
END IF;
END//
DELIMITER;
Try: