Reputation: 1237
I need to insert into TableA from TableB and avoiding duplicates, I tried the below it gives an error:
Violation of Primary Key constraint 'PK_TableA'. Cannot insert duplicate key ...
insert into TableA (DataField, TitleId, ClassId, ValueOrder, StrValue)
select 'Somtext',[title_id],'-1', '1',
[reference_text]
from TableB
where TableB.SomeColumn ='sometext 2014'
TableA
Title_id reference_text
1234 ABCD
1487 XFRE
1434 DERE
TableB
DataField TitleId ClassId ValueOrder StrValue
Now the Problem here is Data already exists in TableB
. I need to avoid when TableA.Tile_id = TableB.TitleId
, when this matches.
Upvotes: 0
Views: 78
Reputation: 7517
Adding a NOT IN
to the WHERE
-clause like this should work:
WHERE TableB.SomeColumn ='sometext 2014'
AND TableB.TitleId NOT IN (SELECT Tile_Id FROM TableA)
Upvotes: 0
Reputation: 11195
Use a where not exists
insert into TableA (DataField, TitleId, ClassId, ValueOrder, StrValue)
select 'Somtext',[title_id],'-1', '1',
[reference_text]
from TableB
where TableB.SomeColumn ='sometext 2014'
and not exists (select 1 from TableA ta where ta.TitleID = TableB.title_id)
Upvotes: 2
Reputation: 548
Take a look at this article, you could do a merge and when matched then (delete/update/insert).
https://www.red-gate.com/simple-talk/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/
Upvotes: 0