How can I delete duplicate rows where no unique row id exists.
Examples:
Create a table called employee.
CREATE TABLE [dbo].[Employee](
[EMPLOYEE_ID] varchar(50) NOT NULL,
[Name] Varchar(100)
)
Insert Records
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('001','Peter')
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('001','Peter')
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('002','Peter')
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('002','Peter')
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('002','Peter')
INSERT INTO dbo.Employee (EMPLOYEE_ID,Name)VALUES
('003','Peter')
Select table:
select * from Employee
Result:
Answer
Insert Identity columns.
ALTER TABLE dbo.Employee ADD AUTOID INT IDENTITY(1,1)
Find out duplicate rows in the table.
SELECT * FROM dbo.Employee WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
FROM dbo.Employee GROUP BY EMPLOYEE_ID,Name)
Delete Duplicate rows.
DELETE FROM dbo.Employee WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
FROM dbo.Employee GROUP BY EMPLOYEE_ID,Name)
Drop Identity column.
alter table Employee drop column autoid
0 Comments