Imagine I have a table Employee with columns id, name, company and a table EmployeeErrorLog with the same structure. The column names of the table Employee will have a unique constraint on the column name. I want to run inserts in the table Employee using SQL. The question is if there is an error triggered during an insert in table Employee, is it possible to make the insert in the table EmployeeErrorLog?
1 Answer
I would look into declare handlers for MySql they basically serve the same purpose as try and catch block.
For more information on these you can check them out here.
http://dev.mysql.com/doc/refman/5.1/en/declare-handler.html
Here is an example of how handlers are used
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @x2 = 1;
-> SET @x = 1;
-> INSERT INTO test.t VALUES (1);
-> SET @x = 2;
-> INSERT INTO test.t VALUES (1);
-> SET @x = 3;
2 Comments
ZeRaTuL_jF
mySql doesn't have try/catch at least not as far as I know but if you check out my edit answer it should get you the same result.
Jorge Campos
@ZeRaTuL_jF You should show an appropriated example instead of providing just a link. Links may break here your answer will be saved.
INSERT ON DUPLICATE KEY UPDATEsyntax you might be interested in. It lets you silently (without errors, that is) update an existing entry if you try to insert it again.