2012-05-30 3 views
0

표 A에는 표 B에서 삭제해야하는 여러 레코드가 포함되어 있습니다. 그러나 표 A의 단일 레코드와 일치하는 표 B의 레코드가 여러 개있을 수 있습니다. 표 B의 첫 번째 일치하는 레코드 만 삭제하려고합니다. 표 A에 표 A에 50 개의 레코드가있는 경우 표 B에서 최대 50 개의 레코드를 삭제해야합니다. 아래 표 A에서 여러 레코드가 삭제되는 SQL 문을 여러 번 사용하여 표 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

관련 문제