简体   繁体   中英

SQL Compare 2 #temp tables and insert the differences into a 3rd #temp table

I have 2 tables A and B with the same structure. I need to get each row from table A that are not present in table B, then insert them into a 3rd #temp table C.

Each table has 2 columns that need to be compared, Type and Step, the remaining columns are RowID, CreatedDate, CreatedUserID, ModifiedDate and ModifiedUserID that do not need to be compared.

Is there a single statement I can use to INSERT INTO #tempC that compares A and B and will insert the values FROM A that are not present in TABLE B using TSQL (SQL SERVER 2012)

SQL 2012 has the EXCEPT statement. Here's a trivial example.

CREATE TABLE #TmpA (
 Col Varchar(10),
 Irrelevant Int );

CREATE TABLE #TmpB (
 Col Varchar(10) );

CREATE TABLE #TmpC (
 Col Varchar(10) );

 INSERT INTO #TmpA 
 SELECT 'A', 0 UNION ALL
 SELECT 'B', 7 UNION ALL
 SELECT 'C', 5 ;

 INSERT INTO #TmpB
 SELECT 'A' UNION ALL
 SELECT 'C' UNION ALL
 SELECT 'D';

 INSERT INTO #TmpC
 SELECT Col FROM #TmpA 
 EXCEPT 
 SELECT Col FROM #TmpB

SELECT * FROM #TmpC;
DROP TABLE #TmpA, #TmpB, #TmpC;

--- And a second scenario following Blams critique

CREATE TABLE #TmpA (
 Col Varchar(10),
 Irrelevant Int );

CREATE TABLE #TmpB (
 Col Varchar(10) );

CREATE TABLE #TmpC (
 Col Varchar(10),
 Irrelevant Int );

 INSERT INTO #TmpA 
 SELECT 'A', 0 UNION ALL
 SELECT 'B', 7 UNION ALL
 SELECT 'C', 5 ;

 INSERT INTO #TmpB
 SELECT 'A' UNION ALL
 SELECT 'C' UNION ALL
 SELECT 'D';

 ;WITH Exceptions AS (
     SELECT Col FROM #TmpA 
     EXCEPT 
     SELECT Col FROM #TmpB
)
INSERT INTO #TmpC
SELECT A.Col, A.Irrelevant 
FROM #TmpA A
JOIN Exceptions E ON A.Col = E.Col

SELECT * FROM #TmpC;
DROP TABLE #TmpA, #TmpB, #TmpC;
insert into #temp3 (Type, Step, RowID ..)
select #temp1.Type, #temp1.Step, #temp1.RowID 
  from #temp1  
  left outer join #temp2 
    on #temp1.Type = #temp2.Type 
   and #temp1.Step = #temp2.Step
 where #temp2.Type is null

Thanks Aaron Bertrand, that is the simplest way, this is my statement:

INSERT INTO #C SELECT WFTypeID, WFStepID FROM #A EXCEPT SELECT WFTypeID, WFStepID FROM #B

Thanks for the other responses guys but that's too much code when you can do it in 1 line :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM