We have a rule engine that is categorizing articles. Currently there is an issue, where we get the following error:
Cannot insert duplicate key row in object 'dbo.article_category' with unique index 'IX_article_category_no_duplicates'. The duplicate key value is (123, 456). The statement has been terminated.
The creation of the entry in article_category
happens in a stored procedure. The main part of the procedure is this:
MERGE article_category AS [target]
USING (
SELECT articleId, @categoryId, @creator, @now, @ruleId, 2
FROM @articleIdList
) AS [source] (articleId, categoryId, creator, createDate, ruleId, assignmentTypeId)
ON (
target.articleId = source.articleId
AND target.categoryId= source.categoryId
)
WHEN NOT MATCHED THEN
INSERT (articleId, categoryId, creator, createDate, ruleId, assignmentTypeId)
VALUES (source.articleId, source.categoryId, source.creator, source.createDate, source.ruleId, source.assignmentTypeId);
When two rules try to insert the same category for the same article, this exception above happens.
How is it possible to stop this from happening? I thought that using the merge
statement instead of if not exists (...)
should prevent this from happening?
Are there other possibilities to prevent this exception?
Thanks in advance