Here's a set based solution using CTEs. Please let us see the execution plans and performance statistics when you have tested them. Best of luck.
Bob
------------------------------------------------
-- CTE Solution
------------------------------------------------
;with cte1 as -- identify breaks
(select code,rowid
from #temptable t1
where t1.code <> (select top 1 code
from #temptable t2
where t2.rowID < t1.rowID
order by t2.rowID desc)
)
,cte2 as -- identify ranges for 'A' codes only
(select c1.code,c1.rowid as minRow,min(c1a.rowID) as maxRow
from cte1 c1
join cte1 c1a on c1a.code <> c1.code and c1a.rowID > c1.rowID
where c1.code = 'A'
group by c1.code,c1.rowID
)
,cte3 as -- identify duplicates in 'A' ranges
(select c.minrow,max(rowid) as dupID
from #temptable t
cross join cte2 c
where t.rowid >=minRow and t.rowID < maxRow
group by c.minRow,t.rowKey,t.locale,c.code
having count(*) > 1
)
,cte4 as -- just get the *first* duplicates
(select min(dupID) as rowID
from cte3
group by minRow
)
,cte5 as -- put the breaks and the first "A" dups together
(select rowID from cte1
union all
select rowID from cte4)
select t.*
from cte5 c
join #temptable t on t.rowID = c.rowID
order by c.rowID
__________________________________________________
Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills