I have a table that I'm trying to add the following constraint to, to avoid duplicates when inserting a duplicate of the constraint columns, but I'm not sure how to get it to not fail the insert entirely on just that duplicate insert attempt, if there are multiple rows being inserted.
This is the constraint I'm adding:
BEGIN
IF NOT EXISTS (SELECT * FROM sys.tables where name = N'T_1321_PNAnnotationCommitReport')
BEGIN
CREATE TABLE AnnotationCommitReport (
[id] [INT] IDENTITY(1,1) PRIMARY KEY not null, --key
[progressnote_id] [INT] NOT NULL,
[form_id] [INT] NOT NULL,
[question_id] [INT],
[question_value] [VARCHAR](max),
[associatedconcept_id] [INT],
[OI_create_date] [DATETIME], --SCHED_RPT_DATE
[crte_date] [DATETIME] DEFAULT CURRENT_TIMESTAMP,
);
--create unique constraint on indicated columns to prevent dups inserted
ALTER TABLE AnnotationCommitReport
ADD CONSTRAINT PN_Unique UNIQUE (progressnote_id, form_id, question_id, question_value, associatedconcept_id, OI_create_date)
END
This is where I add the rows to it that could be duplicated:
INSERT INTO AnnotationCommitReport(progressnote_id,form_id,question_id,question_value,associatedconcept_id, OI_create_date, crte_date)
SELECT progressnote_id,
form_id,
question_id,
questionvalue,
concept_id,
create_date as OI_create_date,
getdate()
FROM FORM_QUESTION
WHERE
(create_date > @LAST_RUN_DATE
AND
create_date <= @RUN_TO_DATE)
END --it's much more complicated than this, so I simplified for this example
How do I make it just not insert that duplicate row? Someone suggested try/catch, but I think it would keep the remainder from being inserted if there are rows to insert after the duplicate row. I found postgresql - avoid duplicate inserts without unique constraint, but I'm not sure if it can be used, and I'm also not sure what they are talking about with a map and how to apply it to what I have.
Update: Here's more detail for that last Insert than I Initially provided:
INSERT INTO dbo.AnnotationCommitReport(progressnote_id,form_id,question_id,question_value,associatedconcept_id, OI_create_date, crte_date)
SELECT progressnote_id,
a.form_id,
question_id,
questionvalue,
fq.concept_id,
a.create_date as OI_create_date,
getdate()
FROM (
SELECT form_id,
progressnote_id,
R.Q.value('@id', 'varchar(max)') AS questionid,
R.Q.value('@value', 'varchar(max)') AS questionvalue,
t.create_date
FROM
@tableNotes t
OUTER APPLY t.form_questions.nodes('/RESULT/QUESTIONS/QUESTION') AS R(Q)
WHERE
ISNUMERIC(R.Q.value('@id', 'varchar(max)')) <> 0
) a
INNER JOIN [CKOLTP_DEV]..FORM_QUESTION fq ON
fq.form_id = a.form_id AND
fq.question_id = a.questionid
WHERE
(a.create_date > @LAST_RUN_DATE
AND
a.create_date <= @RUN_TO_DATE)