Inserting SQL into Union use should add only individual values

So, I have this temp table, which has a structure like:

col1    col2    col3    col3
intID1  intID2  intID3  bitAdd

I am doing a combination of the values ​​of this temp table with a select query and storing it in the same temp table. The fact is that col3 is not part of the join request, I will need to update the table later.

So, I do like this:

Insert into  #temptable
(
intID1,
intID2,
intID3
)
select intID1,intID2,intID3
From
#temptable

UNION

select intID1,intID2,intID3
From
Table A

The problem is that I want to add only rows that do not yet exist in the temp table. As a result, this will add a duplicate of the existing row (since the union will return one row). How to insert only those rows that do not exist in the current temp table in my join request?

+5
source share
3 answers

Nice and easy with EXCEPT

INSERT INTO  #temptable (intID1, intID2, intID3)
SELECT intID1,intID2,intID3 FROM TableA
EXCEPT
SELECT intID1,intID2,intID3 FROM #temptable
+7

MERGE:

MERGE INTO #temptable tmp
USING (select intID1,intID2,intID3 From Table A) t
ON (tmp.intID1 = t.intID1 and tmp.intID2 = t.intID2 and tmp.intID3 = t.intID3)
WHEN NOT MATCHED THEN
INSERT (intID1,intID2,intID3)
VALUES (t.intID1,t.intID2,t.intID3)
+9

, . #temptable ( relvar), ( ) :

#temptable := #temptable UNION A

, .

SQL . SQL DML INSERT ( : - , , , !), .

The answers of Daniel Hilgart and Joachim Isaksson look good. Good practice is to have two good, logically sound candidate answers, and then look for criteria (usually performance at typical load) to eliminate one (but keep it in the comments for future retesting!)

0
source

All Articles