MERGE vs SELECT/INSERT: Choosing an Idempotent Update Strategy Under Azure SQL Retry Policies
0 reputation · 09 Mar 2023, 04:20 UTC
0 reputation · 09 Mar 2023, 04:20 UTC
When a transient error (e.g., 4060, 40197) interrupts a write, Azure SQL’s retry policy can re‑issue the command. The goal is to guarantee that a retry does not produce duplicate rows.
Azure’s retry policy applies to individual SQL statements but not automatically to multi‑statement stored procedures, which can lead to partial re‑execution and unintended duplicates if the logic is not idempotent.
Two documented patterns exist: a single MERGE statement that updates or inserts based on a unique key, and a SELECT‑then‑INSERT sequence guarded by a transaction and optimistic concurrency. Each has trade‑offs around concurrency, trigger behavior, and transaction size.
Will MERGE reliably avoid duplicates when retried after a transient error in the presence of triggers or cascading foreign keys? Does the SELECT/INSERT pattern provide stronger idempotency guarantees when the entire stored procedure is retried? Under Azure SQL’s retry policy, which pattern better handles partial re‑execution of multi‑statement procedures without duplicating writes?
MERGE will not create duplicate rows when retried, but it will re‑execute any AFTER triggers or cascading foreign‑key actions, which can duplicate side‑effects such as audit rows or child updates. The SELECT‑then‑INSERT pattern does not give stronger row‑level idempotency by itself; without additional locking or a unique‑violation check it can still insert twice under retries or concurrent calls.
SET XACT_ABORT ON;.MERGE statement is sufficient; treat any unique‑violation error (2601/2627) as success when the existing row matches the supplied values.sp_getapplock to serialize execution for the same key.Are the AFTER triggers or cascading foreign‑key actions on the target table idempotent, or can they be modified to be so? If they are not, the procedure‑level idempotency step above is required; otherwise a plain MERGE suffices.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.