Is there a way to do something like this in mysql:
INSERT INTO <sometable> SET
someRow = inputSomeValue, someOtherRow = inputValue2 AND
call function1()
ON DUPLICATE KEY ID = inNewID AND
call function2();
Basically, i would like to call some outer mysql stored procedure on “clean” insert, and call some other procedure if insert is obstructed by duplicate key. Is that possible in MySql?
EDIT:
Original insert IS ALREADY in stored procedure!
No. It’s not possible to call a stored procedure from an INSERT statement.
There is a way to call a stored program from an INSERT statement, but it has to be a user defined function, for example:
But that function is going to get called whether the resulting row throws a duplicate key exception or not. It’s also possible to reference a user defined function within the ON DUPLICATE KEY clause.
Note that there are issues with binary logging (row vs. statement) with those constructs, depending on what those functions do, this type of statement may not be “safe” for replication.
So I don’t think you really want to go with this approach. If you are inserting a single row, you are probably going to be better off performing the INSERT … ON DUPLICATE KEY UPDATE … statement, and then checking the number of rows affected. An affected-rows value of 1 will tell you that a row was inserted, an affected-rows value of 2 means the row was updated, so you could conditionally call the procedure you want.
If you always want the actions in those stored procedures called whenever any row is inserted or updated, you might consider AFTER INSERT and AFTER UPDATE triggers. (You need to test to be sure the AFTER UPDATE trigger gets fired from an ON DUPLICATE KEY UPDATE… there were issues in older versions of MySQL where an AFTER UPDATE trigger wasn’t getting called.)
EDIT:
The most recent update to the original question specifies this INSERT statement is performed from within a MySQL stored procedure.
I would recommend this type of approach:
Q: So, after “update” affected rows number will be 0?
A: If no modifications were made to any rows (by the
INSERT ... ON DUPLICATE KEY UPDATEstatement, the ROW_COUNT() function will return 0.If no rows are inserted, and a single row is updated, then the ROW_COUNT() function will return a 2.
The difference between getting a 0 and an 2 is whether the row is actually modified or not. When the result of the update results in the row being identical to the current contents of the row (“no changes made”), then ROW_COUNT() returns a 0. If the update results in a change to the row, the ROW_COUNT() will be 2.