MERGE也可以删除吗?示例仅显示INSERT / UPDATE

时间:2012-08-09 15:18:40

标签: database tsql merge sql-server-2008-r2

我在这里阅读MSDN网站: http://technet.microsoft.com/en-us/library/bb510625.aspx

我对一件事感到有些困惑。

网站上的示例(在底部复制)使用行WHEN NOT MATCHED BY TARGET。我的问题是,我可以使用它在同一个合并中进行插入,更新和删除吗?例如:

--Lazy syntax, but I think you get the idea.
MERGE x AS TARGET USING (ID, [More Fields...]) AS SOURCE
WHEN MATCHED
    update
WHEN NOT MATCHED IN TARGET
    insert
WHEN NOT MATCHED IN SOURCE
    delete

MSDN示例:

USE AdventureWorks2012;
GO
-- Create a temporary table variable to hold the output actions.
DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

MERGE INTO Sales.SalesReason AS Target
USING (VALUES ('Recommendation','Other'), ('Review', 'Marketing'), 
              ('Internet', 'Promotion'))
       AS Source (NewName, NewReasonType)
ON Target.Name = Source.NewName
WHEN MATCHED THEN
    UPDATE SET ReasonType = Source.NewReasonType
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Name, ReasonType) VALUES (NewName, NewReasonType)
OUTPUT $action INTO @SummaryOfChanges;

-- Query the results of the table variable.
SELECT Change, COUNT(*) AS CountPerChange
FROM @SummaryOfChanges
GROUP BY Change;

1 个答案:

答案 0 :(得分:3)

如果你正在进行表的批量交换,那么一种方法是创建两个额外的模式:

CREATE SCHEMA shadow AUTHORIZATION dbo;
CREATE SCHEMA cache  AUTHORIZATION dbo;

现在在cache架构中创建表的副本:

CREATE TABLE cache.SalesReason(Name ...);

现在进行切换操作时:

TRUNCATE TABLE cache.SalesReason;
INSERT cache.SalesReason(Name ...) SELECT ... FROM source;

-- this is a metadata operation so extremely fast - it will wait
-- for existing locks to be released, but won't block new locks
-- for very long at all:

BEGIN TRANSACTION;
  ALTER SCHEMA shadow TRANSFER Sales.SalesReason;
  ALTER SCHEMA Sales TRANSFER  cache.SalesReason;
COMMIT TRANSACTION;

ALTER SCHEMA cache TRANSFER shadow.SalesReason;
TRUNCATE TABLE cache.SalesReason; 
-- truncate is optional - I usually kept the data around for debugging

如果你有外键和其他依赖项,这将无法工作,当然它完全使统计数据等无效,反过来,这会影响计划,但如果最重要的是在你面前获得准确的数据中断最少的用户,这可能是一种需要考虑的方法。