直接来自手册,这是PostgreSQL 中 merge_db 的规范示例:
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');
这可以表示为 MySQL 中的用户定义函数,如果可以,如何表示?与 MySQL 的标准相比有什么优势INSERT...ON DUPLICATE KEY UPDATE
吗?
注意:我专门寻找用户定义的函数,而不是INSERT...ON DUPLICATE KEY UPDATE
.