SQL Server · CrudLabDB
Upsert
Feature 10: insert the row when the code is new, update it when the code already exists - in one
SQL Server MERGE statement.
SQLUpsertService.MERGE_SQL
MERGE article WITH (HOLDLOCK) AS t
USING (SELECT CAST(? AS NVARCHAR(40)) AS code,
CAST(? AS NVARCHAR(200)) AS title,
CAST(? AS NVARCHAR(500)) AS summary,
CAST(? AS NVARCHAR(60)) AS category,
CAST(? AS NVARCHAR(300)) AS tags,
CAST(? AS NVARCHAR(10)) AS priority) AS s
ON t.code = s.code
WHEN MATCHED AND t.locked = 0 THEN
UPDATE SET t.title = s.title,
t.summary = s.summary,
t.category = s.category,
t.tags = s.tags,
t.priority = s.priority,
t.row_version = t.row_version + 1,
t.updated_at = SYSDATETIME()
WHEN NOT MATCHED THEN
INSERT (code, title, summary, category, tags, priority, status, is_read, read_at)
VALUES (s.code, s.title, s.summary, s.category, s.tags, s.priority, N'DRAFT', 1, SYSDATETIME())
OUTPUT $action AS merge_action, inserted.id AS id;
WITH (HOLDLOCK)keeps the key range locked until the end, so two users cannot both INSERT the same code.WHEN MATCHED AND t.locked = 0: a locked row matches but no branch runs, so nothing is returned.OUTPUT $actionreturnsINSERTorUPDATE, which the page shows above.CAST(? AS NVARCHAR(..))gives each parameter a clear type for the comparison.