You could use:
merge into companies (id, version, last_modified)
values(?, coalesce((select version + 1 from companies where id = ?), 0), NOW())
質問
I've got the following table:
create table companies (id identity, version int not null, last_modified timestamp not null);
insert into companies (version, last_modified) values (0, NOW());
I then create a PreparedStatement
and supply a value for index 1:
merge into companies (id, version, last_modified) values(?, version + 1, NOW())
H2 fails with this error:
Column "VERSION" not found
I understand that H2 doesn't like version + 1
on the right-hand side, but it's not clear how to return 0 for new rows and version + 1
for existing rows. Is there an easier way than using a select
statement with a union
?
解決
You could use:
merge into companies (id, version, last_modified)
values(?, coalesce((select version + 1 from companies where id = ?), 0), NOW())
他のヒント
Thomas's answer of
merge into companies (id, version, last_modified)
values(?, coalesce((select version + 1 from companies where id = ?), 0), NOW())
Becomes rather cumbersome if you (as I do) want to conditionally insert or update several fields - you need a coalesce((select ...), default) for each one!
It would appear that a more general answer needs to be two statements:
MERGE INTO companies (id) key (id) VALUES (?)
UPDATE companies SET version=1+IFNULL(version,0), otherfields... WHERE id=?
In other words: don't use MERGE for multiple conditional changes (where you need an expression and not just a value) in a record.
I'd love to be proven wrong on this...