Firebird 2.5 更新或插入

Firebird 2.5 update or insert into

我不知道如何在 Firebird 中编写 SQL 语句,因此它应该添加新行,并且如果满足某些条件还更新其他列。

示例:

(在 MySql 中看起来像这样:)

insert into 
table (col1, col2, col3) values ('a', 'b', 'c')
on duplicate key update col4=col3;

您在 Firebird 中有两个选择

更新或插入

您可以使用 UPDATE OR INSERT:

UPDATE OR INSERT INTO table (col1, col2, col3)
  VALUES ('a', 'b', 'c')
  MATCHING (col1, col2)

MATCHING-子句是可选的。如果您将其省略,它将使用主键:

UPDATE OR INSERT inserts a new record or updates one or more existing records. The action taken depends on the values provided for the columns in the MATCHING clause (or, if the latter is absent, in the primary key). If there are records found matching those values, they are updated. If not, a new record is inserted.

与您问题中的代码相反,这将不允许您自定义更新:它将使用与插入时相同的值。

如果您想要更多控制,请使用合并

合并

MERGE 语句为您提供更多控制权,但可能会更冗长:

MERGE INTO table AS t
  USING (select 'a' as new1, 'b' as new2, 'c' as new3 from rdb$database) as s
    ON t.col1 = s.new1 and t.col2 = s.new2
  WHEN MATCHED THEN 
    UPDATE SET t.col4 = t.col3
  WHEN NOT MATCHED THEN 
    INSERT (col1, col2, col3) values (s.new1, s.new2, s.new3)

然而与UPDATE OR INSERT相反,MERGE不能使用主键。您需要自己在 ON 子句中指定重复规则。