0

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.

3

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

it says invalid object name TableA in the last line
0

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/

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.