We help IT Professionals succeed at work.
Get Started

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

Last Modified: 2018-04-06
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:
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.

Watch Question
Distinguished Expert 2020
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE