2012-05-30 49 views
0

表A包含應從表B中刪除的多個記錄。但是,表B中可能有多個記錄與表A中的單個記錄相匹配。我只想刪除表B中每個記錄的第一個匹配記錄表A.如果表A中有50條記錄,那麼最多50條記錄應該從表B中刪除。我使用下面的SQL語句刪除表B中比表A中列出的更多記錄,這是由於多個匹配。由於數據限制,我無法進一步限制我聲明中的匹配標準。如何爲表A中的每個記錄刪除表B中的第一個匹配記錄?

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

「第一個」是不明確的,直到您告訴我們如何確定排序。應使用表B中的哪些列確定哪一行是「第一」? –

回答

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 
+0

非常感謝你....它的工作....欣賞你的快速幫助! – papfan

相關問題