I need to insert a new row from temp table (temp) if it does not exist in table (t). The problem I have is that there is not a primary key and the temp table is truncated each time its imported. I am merging the data from temp to t with a stored procedure but I only want to import rows that do not exist. I have tried at the start of the insert query:
–IF NOT EXISTS (SELECT * FROM FPS.Predictive_Acquisition_Cost_NEW sa LEFT JOIN FPS_LZ.FPS.Predictive_Acquisition_Cost lz ON lz.Drug_Identifier = sa.Drug_Identifier WHERE sa.Drug_Identifier = lz.Drug_Identifier AND lz.Effective_Date <> sa.Effective_Date)
and at the end of the insert query:
-WHERE NOT EXISTS(SELECT * FROM FPS.Predictive_Acquisition_Cost_NEW)
Full insert query for better reference:
–IF NOT EXISTS (SELECT * FROM FPS.Predictive_Acquisition_Cost_NEW sa LEFT JOIN FPS_LZ.FPS.Predictive_Acquisition_Cost lz ON lz.Drug_Identifier = sa.Drug_Identifier WHERE sa.Drug_Identifier = lz.Drug_Identifier AND lz.Effective_Date <> sa.Effective_Date)
INSERT INTO FPS_SA.FPS.Predictive_Acquisition_Cost_NEW
(
Drug_Identifier,
Identifier_Type,
Drug_Group,
Brand_Generic,
PAC,
PAC_Low,
PAC_High,
PAC_Retail,
Error_Code,
Effective_Date,
End_Date,
PAC_Model_Version
)
SELECT lz.Drug_Identifier,
lz.Identifier_Type,
lz.Drug_Group,
lz.Brand_Generic,
lz.PAC,
lz.PAC_Low,
lz.PAC_High,
lz.PAC_Retail,
lz.Error_Code,
lz.Effective_Date,
lz.End_Date,
lz.PAC_Model_Version
FROM FPS_LZ.fps.Predictive_Acquisition_Cost lz LEFT OUTER JOIN FPS_SA.FPS.Predictive_Acquisition_Cost sa ON lz.Drug_Identifier = sa.Drug_Identifier`
–WHERE NOT EXISTS(SELECT * FROM FPS.Predictive_Acquisition_Cost_NEW)
I tried an "IF NOT EXISTS" at the beginning of the query and/or a "WHERE NOT EXISTS" at the end of the query.
I keep getting duplicate rows in the destination table.
Danica Mattson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.