从SQL中的表中删除结果行

时间:2019-05-09 06:30:11

标签: sql sql-server

我有2个名为BM_Data1BM_Data1_May62019的表。这两个表包含的数据与BM_Data1_May62019表的副本BM_Data1相同。但是BM_Data1有一些额外的行,我该如何从BM_Data1删除那些多余的行,并使它们像BM_Data1_May62019一样。

我使用以下查询获得了额外的行。

SELECT * FROM
(SELECT * FROM BM_DATA1
EXCEPT
SELECT * FROM BM_DATA1_MAY62019) a

还有 7803 个额外的行,如何将它们从BM_Data1表中删除?

谢谢

5 个答案:

答案 0 :(得分:1)

当您确认RECID在两个表中都是通用的且具有唯一值时,您可以尝试以下脚本

DELETE FROM BM_DATA1
WHERE RECID NOT IN
(
    SELECT RECID FROM BM_DATA1_MAY62019
)

答案 1 :(得分:0)

仅使用带有相关子查询的删除

   delete from [BM_DATA1] 
   where not exists 
     (select 1 
    from [BM_DATA1_MAY62019]
    where [BM_DATA1_MAY62019].RECID = [BM_DATA1].RECID -- put here here identified column name
     )

答案 2 :(得分:0)

MERGE中使用WHEN NOT MATCHED BY SOURCE THEN DELETE语句。

MERGE的工作方式类似于JOIN,并且您需要能够确定哪些行相等。您可以通过ON子句来执行此操作-对您来说,就是RECID

我建议您首先在事务中运行这些事务,以便确认仅删除想要的数据-仅在确定配置正确后才提交事务。如果出现问题,可以回滚

BEGIN TRANSACTION

MERGE BM_DATA1 AS Target
USING BM_DATA1_MAY62019as Source 
   ON (Target.RECID = Source.RECID)
WHEN NOT MATCHED BY SOURCE
   THEN DELETE;

SELECT * FROM BM_DATA1

-- ROLLBACK TRANSACTION -- Uncomment and use this if it deleted the wrong data
-- COMMIT -- Uncomment and use this if it deleted the right data!

答案 3 :(得分:0)

我已经包含了一些DDL,因此您可以自己运行它以帮助您理解示例。 ID列是两个表共有的列,您要删除A中不在B中的行

create table #data_a( id int, val int)
create table #data_b( id int, val int)

insert into #data_a select 1, 1 
insert into #data_a select 2, 4 
insert into #data_a select 3, 5 
insert into #data_a select 4, 5 
insert into #data_a select 5, 5 
insert into #data_a select 6, 5 
insert into #data_a select 7, 5 
insert into #data_a select 8, 5 

insert into #data_b select 1, 1 
insert into #data_b select 2, 4 
insert into #data_b select 3, 5 
insert into #data_b select 4, 5 
insert into #data_b select 5, 5 

-- delete the extra rows in A 
delete a from #data_a as a
left join #data_b as b on a.id = b.id
where b.id is null

-- we can see the rows are no longer in B
select * from #data_a
select * from #data_b

drop table #data_a
drop table #data_b

答案 4 :(得分:0)

create table t1(id int, demo int);
create table t2(id int, demo int);

insert into t1 values (1, 1);
insert into t2 values (1, 1);

insert into t1 values (2, 2);
insert into t2 values (2, 2);

insert into t1 values (3, 3);
insert into t2 values (3, 3);

insert into t1 values (4, 4); -- t1 table has some extra rows
insert into t1 values (5, 5); -- t1 table has some extra rows
insert into t1 values (6, 6); -- t1 table has some extra rows

要从第一个表中删除不是第二个表的那些记录,请执行以下操作:

delete from t1 where id not in (select id from t2)