'Creating procedure that add value when it doesn't exist (Syntax error)
I'm trying to create a procedure that add a value that doesn't exist but I'm currently getting a syntax error. I don't know how to correct the error. Any help will be appreciated!
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM Animals WHERE Name = animalName); END' at line 5
Delimiter //
CREATE PROCEDURE AddUniqueName (In animalName varchar(100) )
BEGIN
INSERT INTO Animals (Name)
SELECT animalName
WHERE NOT EXISTS (SELECT * FROM Animals WHERE Name = animalName);
END //
Delimiter ;
Solution 1:[1]
Use INSERT IGNORE statement for uniq keys.
let's assume you have a table
create table Animals( name varchar(255) unique key);
then
Delimiter //
CREATE PROCEDURE AddUniqueName (In animalName varchar(100) )
BEGIN
INSERT IGNORE INTO Animals (Name) values(animalName);
END //
Delimiter ;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eugene Maksymets |