Straight from the manual, here’s the canonical example of merge_db in PostgreSQL:
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- Do nothing, and loop to try the UPDATE again.
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
Can this be expressed as a user-defined function in MySQL, and if so, how? Would there be any advantage over MySQL’s standard INSERT...ON DUPLICATE KEY UPDATE?
Note: I’m specifically looking for a user-defined function, not INSERT...ON DUPLICATE KEY UPDATE.
Tested on MySQL 5.5.14.
Some thoughts:
@ROW_COUNT()because it returns the number of rows actually changed. This could be 0 if the row already has the value you are trying to update.@ROW_COUNT()is not replication safe.REPLACE...INTO.SELECT...FOR UPDATE(untested).I see no advantage to this solution over just using
INSERT...ON DUPLICATE KEY UPDATE.