SQL Server 是否提供类似于 MySQL 的 ON DUPLICATE KEY UPDATE 之类的东西

2021-11-20 00:00:00 tsql mysql sql-server

在 MySQL 中,如果您指定 ON DUPLICATE KEY UPDATE 并且插入的行会导致 UNIQUE 索引或 PRIMARY KEY 中的重复值,则执行旧行的 UPDATE.例如,如果列 a 声明为 UNIQUE 并包含值 1,则以下两个语句具有相同的效果:

In MySQL, if you specify ON DUPLICATE KEY UPDATE and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

我不相信我在 T-SQL 中遇到过类似的事情.SQL Server 是否提供可与 MySQL 的 ON DUPLICATE KEY UPDATE 相媲美的东西?

I don't believe I've come across anything of the like in T-SQL. Does SQL Server offer anything comparable to MySQL's ON DUPLICATE KEY UPDATE?

推荐答案

没有 DUPLICATE KEY UPDATE 等效项,但 MERGE 和 WHEN MATCHED 可能适合您

There's no DUPLICATE KEY UPDATE equivalent, but MERGE and WHEN MATCHED might work for you

使用 MERGE 插入、更新和删除数据

相关文章