• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 455
  • Last Modified:

How to remove duplicates when no primary key

Hi!

How can i remove duplicates from a table.
When i dont have a primary key ?
0
team2005
Asked:
team2005
1 Solution
 
Tapan PattanaikSenior EngineerCommented:
Hi team2005,

Please check this link, here is answer to your question.

Removing Duplicates from a Table in SQL Server:(Tables with no primary key)

http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/
0
 
AnujSQL Server DBACommented:
You can do he following way, if the the table is small and is not a part of replication, mirroring and Logshipping and does not have any references(Foreignkey)

DECLARE @t TABLE
(ID INT, C INT, C2 INT, C3 INT)

INSERT INTO @t
SELECT 1,1,2,4

INSERT INTO @t
SELECT 1,1,2,4
INSERT INTO @t
SELECT 1,1,2,4
INSERT INTO @t
SELECT 3,1,2,4
INSERT INTO @t
SELECT 1,2,2,4
INSERT INTO @t
SELECT 1,2,2,4


SELECT * FROM @t

-- in partition by clause, include all columns
SELECT ID,C,C2,C3
INTO #temp
FROM(
SELECT ROW_NUMBER() OVER(PARTITION BY ID, C, C2, C3 ORDER BY ID) RID,*
FROM @t
) T
WHERE RID = 1

DELETE FROM @t

INSERT INTO @t
SELECT * FROM #temp

SELECT * FROM @t


DROP TABLE #temp

Open in new window

0
 
Tapan PattanaikSenior EngineerCommented:
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
AnujSQL Server DBACommented:
hm, @tapanpattanaik that link looks pretty good, Thanks!
0
 
Ephraim WangoyaCommented:
You can simply partition by the fields you consider to be duplicates then delete from the cte directly, say field1, field2, field3 define your duplicates

;with ctedelete as
(
  select *, row_number() over (partition by field1, field2, field3 order by field1) rn
  from yourtable
)

delete 
from ctedelete
where rn > 1

Open in new window

0
 
team2005Author Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now