Skip to content

Instantly share code, notes, and snippets.

@liuzy163
Created June 5, 2015 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuzy163/727c9c793f51a6288896 to your computer and use it in GitHub Desktop.
Save liuzy163/727c9c793f51a6288896 to your computer and use it in GitHub Desktop.
Use CTE and Table Partition and Ranking Functions to Delete Rows with Duplicates
create procedure dbo.fixDuplication(@accountNumber varchar(255), @productId varchar(30))
as
begin
WITH CTE as
(
select oli.id, oli.serialNumber, row_number()
over (partoliion by serialNumber order by serialNumber) as rownumber
from orderLineItems as oli
join orders as o on o.id=oli.orderId
where o.accountnumber = @accountnumber
and oli.productId=@productId
and oli.serialNumber is not null
)
delete oli
output deleted.*
from orderLineoliems as oli
join CTE as c on c.id=oli.id
where rownumber>1
end
go
exec dbo.fixDuplication @accountNumber='12345', @productId='IPAD_1234';
[/code]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment