0

表A包含应该从表B中删除的多条记录。但是,表B中可以有多个记录匹配表A中的单个记录。我只想删除表B中第一个匹配的记录为表A中的每条记录. 如果表 A 中有 50 条记录,则应从表 B 中删除最多 50 条记录。我正在使用下面的 SQL 语句,由于多个匹配项,从表 B 中删除的记录多于表 A 中列出的记录。由于数据的限制,我无法在我的陈述中进一步限制匹配标准。

DELETE FROM [#DraftInvoiceRecords] FROM [#DraftInvoiceRecords]
INNER JOIN [#ReversedRecords]
ON [#DraftInvoiceRecords].employee = [#ReversedRecords].employee 
  and [#DraftInvoiceRecords].amount = [#ReversedRecords].amount
  and [#DraftInvoiceRecords].units = [#ReversedRecords].units
4

1 回答 1

0

您需要一些方法来区分要删除的行和要保留的行。我someOtherColumn在下面使用来实现这一点:

create table #DraftInvoiceRecords (
    employee int not null,
    amount int not null,
    units int not null,
    someOtherColumn int not null
)
create table #ReversedRecords (
    employee int not null,
    amount int not null,
    units int not null
)
insert into #DraftInvoiceRecords (employee,amount,units,someOtherColumn)
select 1,1,1,1 union all
select 1,1,1,2
insert into #ReversedRecords (employee,amount,units)
select 1,1,1
delete from dir
from
    #DraftInvoiceRecords dir
        inner join
    #ReversedRecords rr
        on
            dir.employee = rr.employee and
            dir.amount = rr.amount and
            dir.units = rr.units
        left join
    #DraftInvoiceRecords dir_anti
        on
            dir.employee = dir_anti.employee and
            dir.amount = dir_anti.amount and
            dir.units = dir_anti.units and
            dir.someOtherColumn > dir_anti.someOtherColumn --It's this condition here that allows us to distinguish the rows
where
    dir_anti.employee is null

select * from #DraftInvoiceRecords

drop table #DraftInvoiceRecords
drop table #ReversedRecords
于 2012-05-30T06:48:19.837 回答