We have a process updating the database which uses the following SQL
IF NOT EXISTS (SELECT * FROM Target_Table WHERE Target_Table_ID = ...)
BEGIN
INSERT ...
END
ELSE
BEGIN
UPDATE ...
END
I wanted to change this to use a MERGE
statement in order to avoid a possible race condition where the IF
and then INSERT
or UPDATE
statements are evaluated separately.
However, as soon as I executed the query I got the error:
The target table 'Target_Table' of the MERGE statement cannot have any enabled rules. Found rule 'TargetTable_RULE'
I understand the documentation states that the table cannot have rules enabled, although I missed it when first reading it, and apart from disabling the rule before performing the MERGE
(which I don't see as a workable solution) it seems I'm stuck with the IF NOT EXISTS
solution.
What the document does not explain is why the target table is not allowed to have rules. In my case the rule is a simple > 0
check on a value.
Does anyone know why rules are not allowed in this situation and if there is another way to perform the upsert in an atomic way?
EDIT: As Andriy M commented the question Atomic UPSERT in SQL Server 2005 already has a wealth of information on atomic upserts so I'll not duplicate the discussion here. Instead I'd like just to know why the MERGE
statement cannot execute on tables with rules defined and is there a work-around?