提交 6aa21ffb authored 作者: Thomas Mueller's avatar Thomas Mueller

The MERGE statement now returns 0 as the generated key if the row was updated.

上级 198d7b24
......@@ -24,6 +24,7 @@ import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.util.ObjectArray;
import org.h2.value.Value;
import org.h2.value.ValueLong;
/**
* This class represents the statement
......@@ -106,6 +107,7 @@ public class Merge extends Prepared {
String sql = buff.toString();
update = session.prepare(sql);
setCurrentRowNumber(0);
session.setLastIdentity(ValueLong.get(0));
if (list.size() > 0) {
count = 0;
for (int x = 0; x < list.size(); x++) {
......
......@@ -82,8 +82,9 @@ MERGE INTO tableName [(columnName [,...])] [KEY(columnName [,...])]
Updates the row if it exists, and if the row does not exist, inserts a new row.
If the key columns are not specified, the primary key columns are used to find the row.
This command is sometimes called 'UPSERT' as it updates a row if it exists,
or inserts the row if it does not yet exist.
If more than one row per new row is affected, an exception is thrown.
or inserts the row if it does not yet exist. If more than one row per new row is affected,
an exception is thrown. If the table contains an auto-incremented key or identity column, a
nd the row was updated, the generated key is set to 0; otherwise it is set to the new key.
","
MERGE INTO TEST KEY(ID) VALUES(2, 'World')
"
......
......@@ -43,6 +43,7 @@ public class TestStatement extends TestBase {
testConnectionRollback();
testStatement();
if (config.jdk14) {
testIdentityMerge();
testIdentity();
}
conn.close();
......@@ -318,6 +319,29 @@ public class TestStatement extends TestBase {
stat.close();
}
private void testIdentityMerge() throws SQLException {
Statement stat = conn.createStatement();
stat.execute("drop table if exists test1");
stat.execute("create table test1(id identity, x int)");
stat.execute("drop table if exists test2");
stat.execute("create table test2(id identity, x int)");
stat.execute("merge into test1(x) key(x) values(5)");
ResultSet keys;
keys = stat.getGeneratedKeys();
keys.next();
assertEquals(1, keys.getInt(1));
stat.execute("insert into test2(x) values(10), (11), (12)");
stat.execute("merge into test1(x) key(x) values(5)");
keys = stat.getGeneratedKeys();
keys.next();
assertEquals(0, keys.getInt(1));
stat.execute("merge into test1(x) key(x) values(6)");
keys = stat.getGeneratedKeys();
keys.next();
assertEquals(2, keys.getInt(1));
stat.execute("drop table test1, test2");
}
private void testIdentity() throws SQLException {
Statement stat = conn.createStatement();
stat.execute("CREATE SEQUENCE SEQ");
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论