I am using a trigger to create a sequence number, the secondary field on a primary key. The trigger works when I manually input records into the table but I get the following error when I use an INSERT/SELECT : Server: Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK_CRIntrvsC'. Cannot insert duplicate key in object 'CRIntrvsC'.
The statement has been terminated. How can I fix this?
Thanks
Trigger Code:
CREATE TRIGGER [IntrvSeqNbr] ON [dbo].[CRIntrvsC]
FOR INSERT
AS
IF EXISTS (SELECT cr_cse_id FROM Inserted WHERE intrvention_seq_nbr=0)
BEGIN
DECLARE @seq INT
SELECT @seq=MAX(CRI.intrvention_seq_nbr)+1
FROM CRIntrvsC CRI
INNER JOIN Inserted I
ON CRI.cr_cse_id = I.cr_cse_id
UPDATE CRIntrvsC
SET intrvention_seq_nbr = @seq
FROM CRIntrvsC CRI
INNER JOIN Inserted I
ON CRI.cr_cse_id = I.cr_cse_id
AND CRI.intrvention_seq_nbr=I.intrvention_seq_nbr
END
Insert Code:
INSERT INTO CrIntrvsC (cr_cse_id
, intrvention_seq_nbr
, intrvention_src_cd
, intrvention_id
, actv_rsn_cd
, actv_typ_cd
, otcome_typ_cd
, PARS_intrvention_catgy_cd
, PARS_intrvention_cd
, intrvention_cnt
)
SELECT cr_cse_id
, 0
, 'P'
, NULL
, NULL
, NULL
, NULL
, PARS_intrvention_catgy_cd
, PARS_intrvention_cd
, (SELECT COUNT(*) FROM xParsIntrvWindowC piw
WHERE piw.rev_key = cse.rev_key)
FROM CrCaseC cse
INNER JOIN xParsIntrvWindowC piw1
ON cse.rev_key = piw1.rev_key
Violation of PRIMARY KEY constraint 'PK_CRIntrvsC'. Cannot insert duplicate key in object 'CRIntrvsC'.
The statement has been terminated. How can I fix this?
Thanks
Trigger Code:
CREATE TRIGGER [IntrvSeqNbr] ON [dbo].[CRIntrvsC]
FOR INSERT
AS
IF EXISTS (SELECT cr_cse_id FROM Inserted WHERE intrvention_seq_nbr=0)
BEGIN
DECLARE @seq INT
SELECT @seq=MAX(CRI.intrvention_seq_nbr)+1
FROM CRIntrvsC CRI
INNER JOIN Inserted I
ON CRI.cr_cse_id = I.cr_cse_id
UPDATE CRIntrvsC
SET intrvention_seq_nbr = @seq
FROM CRIntrvsC CRI
INNER JOIN Inserted I
ON CRI.cr_cse_id = I.cr_cse_id
AND CRI.intrvention_seq_nbr=I.intrvention_seq_nbr
END
Insert Code:
INSERT INTO CrIntrvsC (cr_cse_id
, intrvention_seq_nbr
, intrvention_src_cd
, intrvention_id
, actv_rsn_cd
, actv_typ_cd
, otcome_typ_cd
, PARS_intrvention_catgy_cd
, PARS_intrvention_cd
, intrvention_cnt
)
SELECT cr_cse_id
, 0
, 'P'
, NULL
, NULL
, NULL
, NULL
, PARS_intrvention_catgy_cd
, PARS_intrvention_cd
, (SELECT COUNT(*) FROM xParsIntrvWindowC piw
WHERE piw.rev_key = cse.rev_key)
FROM CrCaseC cse
INNER JOIN xParsIntrvWindowC piw1
ON cse.rev_key = piw1.rev_key