I'm required to move every unique row from TableA
to TableB
, if the unique row from TableA
is not already in TableB
.
Both tables look the same, they don't have any key
s, but there's a combination of columns that make their rows unique for my task – num
which is an int
and com
, a varbinary(512)
.
As my SQL is horrible I wanted to create a script that does the job, but I have ridiculous problems, escaping/handling the varbinary
value. This is why I'm asking for help.
I can pseudo-code..
moving/copying::
SELECT * INTO TableB
WHERE (unique TableA.num + TableA.com)
AND NOT IN (TableB)
FROM TableA
afterwards, for moving only
DELETE FROM TableA WHERE (unique from above)
(Working on Microsoft SQL Server Enterprise Edition v9.00.3042.00, i.e. SQL Server 2005 Service Pack 2)
Additional details
Sorry. I'm still learning SQL AND asking proper questions..
TableA
& TableB
have the same design. They have multiple columns, including the two above mentioned ones. I'm required to both move and copy (depending on the chosen option). TableA
is the source, TableB
is the destination. Both tables may contain numerous occurrences of the same int/com combination. I need to have only one (it doesn't matter which one) of each of the combinations. With copying they're not removed from TableA
, when moving, they should be.
Best Answer
If I can understand correctly what you are looking to do, you want to
SELECT
all records fromTableA
that only appear once, but don't already appear inTableB
.You can do this with a
GROUP BY
andHAVING
to identify those that only appear once inTableA
, then do anEXCEPT
to filter out those that already appear inTableB
.If you actually wanted to
SELECT
ALL distinct records fromTableA
(regardless of how many times they occur inTableA
) that do not already appear inTableB
,then you could use theDISTINCT
keyword.Edit: As @ypercube correctly pointed out,
EXCEPT
already filters forDISTINCT
rowsIf the two tables have more columns, it's handier to use
NOT EXISTS
instead ofEXCEPT
. You could also useROW_NUMBER()
to select an arbitrary row in 2005+ versions. So, the copying from table A to B would be: