Reputation: 9986
This is my table:
I do this request:
UPDATE efep SET efep.ID_ETAT_PERSONNE = 9
FROM ETAT_FICHE_ETAT_PERSONNE efep
WHERE efep.ID_ETAT_PERSONNE IN (2,3,7) AND NOT EXISTS (
SELECT 1
FROM ETAT_FICHE_ETAT_PERSONNE efep2
WHERE efep2.ID_ETAT_PERSONNE = 9 and efep2.ID_ETAT_PERSONNE = efep.ID_ETAT_PERSONNE);
I have this error:
Msg 2627, Level 14, State 1, Line 127
Violation of PRIMARY KEY constraint 'PK_ETAT_FICHE_ETAT_PERSONNE'. Can not insert duplicate key in object 'dbo.ETAT_FICHE_ETAT_PERSONNE'.
The statement has been terminated.
Why is wrong ..?
Primary Key:
ALTER TABLE [dbo].[ETAT_FICHE_ETAT_PERSONNE] ADD CONSTRAINT [PK_ETAT_FICHE_ETAT_PERSONNE] PRIMARY KEY CLUSTERED
(
[ID_ETAT_FICHE] ASC,
[ID_ETAT_PERSONNE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
Upvotes: 1
Views: 85
Reputation: 69514
I think its pretty simple your where clause will end up returning all the rows (rows shown in your example).
And if you are update ID_ETAT_PERSONNE
column to 9
you will end up with duplicates like .
ID_ETAT_PERSONNE ID_ETAT_PERSONNE
1 9
1 9
2 9
2 9
3 9
3 9
Since you have a composite primary key on these two tables, it will error out.
The logic you are trying to implement cannot be done, you will end up with duplicate Primary key values.
You can do an insert of value 9
for [ID_ETAT_PERSONNE]
column where it meets your criteria.
INSERT INTO ([ID_ETAT_FICHE] , [ID_ETAT_PERSONNE])
SELECT efep.[ID_ETAT_FICHE] , 9
FROM ETAT_FICHE_ETAT_PERSONNE efep
WHERE efep.ID_ETAT_PERSONNE IN (2,3,7)
AND NOT EXISTS (SELECT 1
FROM ETAT_FICHE_ETAT_PERSONNE efep2
WHERE efep2.ID_ETAT_PERSONNE = 9
and efep2.[ID_ETAT_FICHE] = efep.[ID_ETAT_FICHE])
GROUP BY efep.[ID_ETAT_FICHE]
Upvotes: 0
Reputation: 40481
I think its a typo inside the EXISTS()
:
WHERE efep2.ID_ETAT_PERSONNE = 9 and efep2.ID_ETAT_PERSONNE = efep.ID_ETAT_PERSONNE);
Isn't it supposed to be :
WHERE efep2.ID_ETAT_PERSONNE = 9 and efep2.ID_ETAT_FICHE = efep.ID_ETAT_FICHE);
Looks like you connect the record by the wrong column, so you actually checked something like:
WHERE efep2.ID_ETAT_PERSONNE = 9 and efep2.ID_ETAT_PERSONNE = 7/2/3
Which is not possible and will always be false, therefore - won't work.
As @M.Ali pointed up, this logic can not be done like this, even with this change, you will still end up with duplicates key as long as you have more then 1 record with the same ID_ETAT_PERSONNE in(2,3,7)
Upvotes: 1