In MySQL, how do I do an insert based upon whether or not a row already exists in a table? The SQL below doesn't seem to work, so I'm looking for another way to accomplish this. Below is all of the code that I have so far (I'm in the process of converting this from MS SQL). I'm sure there are several things wrong with it, but I am specifically looking for the if not exists syntax. If anyone would like to take a shot at making the whole thing work, then I won't complain. :)
CREATE PROCEDURE INTRA_UpdateEmployee (
in_Action varchar(10),
in_ID int,
in_FirstName varchar(255),
in_LastName varchar(50),
in_Company int,
in_Department int,
in_Title varchar(255),
in_Supervisor varchar(1),
in_EmailAddress varchar(255),
in_OfficePhone varchar(15),
in_HomePhone varchar(15),
in_CellPhone varchar(15),
in_FaxNumber varchar(15),
in_IMName varchar(50)
)
sp:BEGIN
IF in_Action = 'insert'
IF NOT EXISTS (Select ID From employees Where ID = in_ID)
THEN
Insert Into employees (ID, Name, Password, InActive, Extension)
Values (in_Action, in_ID, in_FirstName, in_LastName, in_Company, in_Department, in_Title, in_Supervisor, in_EmailAddress, in_OfficePhone, in_HomePhone, in_CellPhone, in_FaxNumber, in_IMName);
Select 'Insert Successful.' as Message;
leave sp;
ELSE
Select 'There is already a user with this name.' as Message;
leave sp;
END IF
END
ELSEIF in_Action = 'update'
IF EXISTS (Select ID From Users Where ID = in_ID)
Update employees
Set firstname = in_FirstName,
lastname = in_LastName,
company = in_Company,
department in_Department,
title = in_Title,
supervisor = in_Supervisor,
emailaddress = in_EmailAddress,
officephone = in_OfficePhone,
homephone = in_HomePhone,
cellphone = in_CellPhone,
faxnumber = in_FaxNumber,
imname = in_IMName
Where ID = in_ID;
Select 'Update Successful.' as Message;
leave sp;
END IF
ELSE
Select 'Invalid Action.' as Message
leave sp;
END IF
END
by: todd_farmerPosted on 2007-03-19 at 07:53:09ID: 18748451
Does the table have a primary or unique key (it appears not)? If it does, you can use INSERT IGNORE ....
If it does not, create a UNIQUE constraint on the combination of columns that need to be identical, then use INSERT IGNORE.