且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在SQL Server 2005中使用MERGE语句吗?

更新时间:2022-01-30 22:19:40

MERGE 是SQL Server 2008中引入的.如果要使用该语法,则需要升级.

MERGE was introduced in SQL Server 2008. If you want to use that syntax, you'll need to upgrade.

否则,典型方法将取决于源数据的来源.如果只有一行,并且您不知道是否需要更新或插入,则可能需要这样做:

Otherwise, the typical approach will depend on where the source data is from. If it's just one row and you don't know if you need to update or insert, you'd probably do:

UPDATE ... WHERE key = @key;

IF @@ROWCOUNT = 0
BEGIN
    INSERT ...
END

如果源是#temp表,表变量,TVP或其他表,则可以执行以下操作:

If your source is a #temp table, table variable, TVP or other table, you can do:

UPDATE dest SET ...
  FROM dbo.destination AS dest
  INNER JOIN dbo.source AS src
  ON dest.key = src.key;

INSERT dbo.destination SELECT ... FROM dbo.source AS src
  WHERE NOT EXISTS (SELECT 1 FROM dbo.destination WHERE key = src.key);

MERGE一样(以及 Michael Swart在此处演示),您将仍然想用适当的事务,错误处理和隔离级别将所有这些方法包围起来,使其表现得像真正的单一操作.甚至只有一个MERGE语句也不能保护您避免并发.

As with MERGE (and as Michael Swart demonstrated here), you will still want to surround any of these methods with proper transactions, error handling and isolation level to behave like a true, single operation. Even a single MERGE statement does not protect you from concurrency.

我已经在此处发布了有关MERGE的其他注意事项.