我们有一个更新数据库的进程,它使用以下SQL
IF NOT EXISTS (SELECT * FROM Target_Table WHERE Target_Table_ID = ...)
BEGIN
INSERT ...
END
ELSE
BEGIN
UPDATE ...
END
我想将此更改为使用MERGE
语句,以避免可能的竞争条件,其中IF
然后INSERT
或UPDATE
语句将单独计算。
但是,只要我执行了查询,就会收到错误:
MERGE语句的目标表'Target_Table'不能具有任何已启用的规则。找到规则'TargetTable_RULE'
我理解文档说明该表不能启用规则,虽然我在第一次阅读时错过了它,除了在执行MERGE
之前禁用规则(我认为这不是一个可行的解决方案) )似乎我坚持使用IF NOT EXISTS
解决方案。
该文档未解释的是为什么目标表不允许有规则。在我的情况下,规则是对值的简单> 0
检查。
有没有人知道为什么在这种情况下不允许使用规则,以及是否有其他方式以原子方式执行upsert?
编辑:正如Andriy M评论的问题Atomic UPSERT in SQL Server 2005已经有关于原子upsert的大量信息所以我不会在这里重复讨论。相反,我想知道为什么MERGE
语句无法在已定义规则的表上执行,是否有解决办法?
答案 0 :(得分:6)
MERGE
语句不支持带规则的表的原因。 MERGE示例(带有CHECK
约束的规则&):
CREATE RULE MyRule
AS
@Status IN ('Y', 'N');
GO
CREATE TABLE dbo.SalesOrder
(
SalesOrderID INT PRIMARY KEY
,OrderDate DATETIME NOT NULL
,IsDeleted CHAR(1) NOT NULL DEFAULT 'N'
);
GO
EXEC sp_bindrule @rulename='MyRule', @objname='dbo.SalesOrder.IsDeleted';
GO
INSERT dbo.SalesOrder (SalesOrderID, OrderDate)
SELECT 1, '20110101'
UNION ALL
SELECT 2, '20110202'
UNION ALL
SELECT 3, '20110303';
GO
SELECT *
FROM dbo.SalesOrder;
PRINT '*****First test*****';
GO
MERGE dbo.SalesOrder Dst
USING (VALUES (1,'Y'), (4,'Y')) AS Src(SalesOrderID, IsDeleted)
ON Dst.SalesOrderID = Src.SalesOrderID
WHEN MATCHED THEN UPDATE SET IsDeleted = Src.IsDeleted
WHEN NOT MATCHED BY TARGET THEN INSERT (SalesOrderID, OrderDate, IsDeleted) VALUES (Src.SalesOrderID, GETDATE(), Src.IsDeleted);
GO
EXEC sp_unbindrule 'dbo.SalesOrder.IsDeleted'; --Disabling `MyRule` for IsDeleted column
ALTER TABLE dbo.SalesOrder --We "replace" the old rule with a new `CHECK` constraint
ADD CONSTRAINT CK_SalesOrder_IsDeleted CHECK( IsDeleted IN ('Y', 'N') );
GO
PRINT '*****Second test*****';
MERGE dbo.SalesOrder Dst
USING (VALUES (1,'Y'), (4,'Y')) AS Src(SalesOrderID, IsDeleted)
ON Dst.SalesOrderID = Src.SalesOrderID
WHEN MATCHED THEN UPDATE SET IsDeleted = Src.IsDeleted
WHEN NOT MATCHED BY TARGET THEN INSERT (SalesOrderID, OrderDate, IsDeleted) VALUES (Src.SalesOrderID, GETDATE(), Src.IsDeleted);
GO
SELECT *
FROM dbo.SalesOrder;
DROP TABLE dbo.SalesOrder;
DROP RULE MyRule;
结果:
Rule bound to table column.
(3 row(s) affected)
SalesOrderID OrderDate IsDeleted
------------ ----------------------- ---------
1 2011-01-01 00:00:00.000 N
2 2011-02-02 00:00:00.000 N
3 2011-03-03 00:00:00.000 N
(3 row(s) affected)
*****First test*****
Msg 358, Level 16, State 1, Line 2
The target table 'Dst' of the MERGE statement cannot have any enabled rules. Found rule 'MyRule'.
Rule unbound from table column.
*****Second test*****
(2 row(s) affected)
SalesOrderID OrderDate IsDeleted
------------ ----------------------- ---------
1 2011-01-01 00:00:00.000 Y
2 2011-02-02 00:00:00.000 N
3 2011-03-03 00:00:00.000 N
4 2011-09-20 16:03:56.030 Y
(4 row(s) affected)