如何删除2个表的重复行,只有2个表比较SQL Server

时间:2017-02-01 09:42:18

标签: sql-server

我希望存储过程基于2列table_A创建一个临时表,然后检查table_B(有5列)中是否有包含这两列的行,就像它们的方式一样在table_A。不要对他们做任何不重复的删除行。

这样的事情:

Create Procedure DeleteExtra

as

Create Table #TempTotalHoney
(
HarvestDate Date,
HoneyType VarChar(50)
)

INSERT INTO #TempTotalHoney
Select HarvestDate, HoneyType
From tHoneyHarvest
Group BY HarvestDate, HoneyType

//until here temptable created as I want, but I don't know how to check
//not duplicated rows, I tried this But it is wrong...

Delete From tHoneyWeight
Where HarvestDate AND HoneyType Not in (select HarvestDate, HoneyType 
From #TempTotalHoney)

//must check these tow columns together not separately  


If(OBJECT_ID('tempdb..#TempTotalHoney') Is Not Null)
Begin
    Drop Table #TempTotalHoney
End

这是我得到的错误:

  

Msg 4145,Level 15,State 1,Procedure DeleteExtra,第17行
  在预期条件的上下文中指定的非布尔类型的表达式,接近' AND'。

更新

this is #TempTotalHoney that created from table_A

HarvestDate           HoneyType
---------------------------------------------------
2017-01-10            Pure
2017-01-10            Semi-Pure
2017-02-03            Pure
2017-02-04            artificial 

table_B:

RecID      HarvestDate    HoneyType   TotalCombs    TotalWeight
----------------------------------------------------------------
 1         2017-01-10     Pure            10           22
 3         2017-01-10     Semi-Pure       11           24
 4         2017-02-03     Pure            22           50
 6         2017-02-04     artificial      25           56
 8         2017-01-10     Semi-Art        10           18.5
 9         2017-02-05     Pure            11           19

我希望RecID 8和9中删除#TempTotalHoney中不存在HarvestDate和HoneyType的组合。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用以下查询

DELETE table_B
FROM table_B B
 LEFT JOIN #TempTotalHoney A 
  ON B.HarvestDate = A.HarvestDate 
   AND B.HoneyType = A.HoneyType
WHERE A.HoneyType is Null;

希望这会帮助你。