I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE
or INSERT ... ON DUPLICATE KEY UPDATE
in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).
So far the best I came up with is just doing:
UPDATE table SET data='data' WHERE key='key';
INSERT INTO table(key, data) VALUES ('key', 'data');
one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?