I think that your first INSERT ... SELECT
statement is producing duplicates and then these duplicates are causing primary key errors in your second select. Your WHERE EXISTS
clause only guards against inserting a duplicate that is a duplicate of an existing row.
I will come to your query later, but just to show you can cause this error quite simply with the following set of statements:
create table TableA
(
Pid INT PRIMARY KEY,
etc INT
);
INSERT INTO TableA
SELECT 1, 0
UNION
SELECT 1, 2
and here is the error:
Violation of PRIMARY KEY constraint 'PK__TableA__C57059387F60ED59'. Cannot insert duplicate key in object 'dbo.TableA'.: INSERT INTO TableA SELECT 1, 0 UNION SELECT 1, 2
Now back to your query, the simple re-write is to ensure that the query only returns DISTINCT
rows:
INSERT INTO #tr_TxnDetails
SELECT DISTINCT
b.pid,
b.etc
FROM tbl_SomeTableA as a
JOIN tbl_SomeTableB as b ON a.etc = b.etc
AND a.SomeColumn = b.SomeColumn
INSERT INTO tr_TxnDetails
([id], [etc])
SELECT a.[id],
a.[etc]
FROM #tr_TxnDetails as a
WHERE not exists (select 1 from tr_TxnDetails as b where a.[id] = b.[id]);
This should do the trick for you.
One further point is that in your example you should do away with the temporary table step unless there is a good reason for it, such as some other processing between those two statements. Here is the rewritten query:
INSERT INTO tr_TxnDetails
SELECT DISTINCT
b.pid,
b.etc
FROM tbl_SomeTableA as a
JOIN tbl_SomeTableB as b ON a.etc = b.etc
AND a.SomeColumn = b.SomeColumn
WHERE not exists (
select 1
from tr_TxnDetails as c
where a.[id] = C.[id]
);