1

I have been looking into questions with duplicate rows, but haven't seen anything that matches my case. Furthermore, I am fairly new to SQL Server so I apologize if I don't make much sense.

So I have an existing table (lets say TableA) that holds historical information. I have a query that runs every Sunday and creates a table, only with input from the previous week (Saturday to Friday) and stores it in another table (TableB).

I am updating TableA with data from TableB every Sunday and I am using INSERT INTO, which works. However sometimes I might have to run the query manually mid-week in which case I might get duplicates on Sunday.

How exactly do I write the INSERT INTO so I don't get duplicate rows and keep the values from the latest execution query?

jarlh
  • 42,561
  • 8
  • 45
  • 63
Andrew
  • 13
  • 2
  • you can do an **upsert** action: https://stackoverflow.com/questions/11010511/how-to-upsert-update-or-insert-in-sql-server-2005 – jacktrade Jan 30 '19 at 07:47

2 Answers2

0

You have not provided details of your schema, but easiest way to check duplicate before insert is using NOT EXISTS like following sample query.

INSERT INTO TARGET_TABLE (Col1, Col2 ...)
SELECT Col1, Col2 .. FROM [SOURCE] S
WHERE NOT EXISTS
(
  SELECT 1 FROM TARGET_TABLE T WHERE T.UniqueIdentifierColumn= S.UniqueIdentifierColumn
)
PSK
  • 17,547
  • 5
  • 32
  • 43
0

Try this one:

INSERT INTO TABLEA(Col1, Col2 ...)
SELECT Col1, Col2 ... FROM TABLEB
EXCEPT
SELECT Col1, Col2 ... FROM TABLEA
Mano
  • 780
  • 3
  • 15