SQL比较2个#temp表并将差异插入第3个#temp表

时间:2014-02-11 20:41:45

标签: sql tsql compare sql-server-2012

我有两张表A和B,结构相同。我需要从表A中获取表B中不存在的每一行,然后将它们插入到第3个#temp表C中。

每个表都有2列需要比较,Type和Step,其余列是RowID,CreatedDate,CreatedUserID,ModifiedDate和ModifiedUserID,不需要比较。

我是否可以使用单个语句来INSERT INTO #tempC来比较A和B,并使用TSQL插入表B中不存在的值FROM A(SQL SERVER 2012)

3 个答案:

答案 0 :(得分:2)

SQL 2012具有EXCEPT语句。这是一个微不足道的例子。

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;

---继布莱姆斯批评之后的第二种情景

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;

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

感谢Aaron Bertrand,这是最简单的方法,这是我的陈述:

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

感谢其他回复的人,但是当你可以在1行中做太多的代码:)