T-SQL Is it possible to do an Update / Insert with a single fast operation

隐身守侯 提交于 2019-12-03 14:29:46

SQL Server 2008 and newer have a MERGE statement which does exactly that.

See the MSDN Books Online docs on MERGE for details.

Basically, you need four things:

  • a source (table or view or inline SELECT statement)
  • a target
  • a JOIN condition that links the two
  • statements for cases when there's a MATCH (rows exists in both source and target), NOT MATCHED (when row doesn't exist in the target yet) and so forth

So you basically define something like:

MERGE (targettable) AS t
USING (sourcetable) AS s
ON (JOIN condition between s and t)
WHEN MATCHED THEN
   UPDATE SET t.Col1 = s.Col1, t.Col2 = s.Col2 (etc.)
WHEN NOT MATCHED THEN
   INSERT(Col1, Col2, ..., ColN) VALUES(s.Col1, s.Col2, ......, s.ColN)

This is done as one statement and highly optimized by SQL Server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!