Link to home
Start Free TrialLog in
Avatar of programmerist 1983
programmerist 1983Flag for Türkiye

asked on

How can I delete dublicated rows by using for loop in SQL?

Hi; I have a dublicated rows table like below.
	 SELECT count(*) ,d.SapContractNumber, d.MaterialNumber, d.SapDeliveryNumber, d.Batch
                     FROM  DeliveryItems d 
                     GROUP BY
                                 d.SapContractNumber, d.MaterialNumber, d.SapDeliveryNumber, d.Batch HAVING COUNT(*) >1

Open in new window

Above Query Result:
User generated image
My removing query for dublicated rows below:

      delete from DeliveryItems  where  SapContractNumber = '3120009625' and MaterialNumber = '03002721122' and SapDeliveryNumber = '3140095689' and Batch = '61974301'
 and Id NOT IN
               (SELECT max(d.Id)
                     FROM  DeliveryItems d  where  d.SapContractNumber = '3120009625' and d.MaterialNumber = '03002721122' and d.SapDeliveryNumber = '3140095689' and d.Batch = '61974301'
                     GROUP BY
                            d.SapContractNumber, d.MaterialNumber, d.SapDeliveryNumber, d.Batch

Open in new window

My Question is here! How can i do that by using above query(First Query)result to remove dublicated rows. I have to use second query inside of the a for loop (FETCH NEXT) to push (SapContractNumber,MaterialNumber ,SapDeliveryNumber,Batch ) from First query.

User generated image
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of programmerist 1983


Best Answer Thanks...