I have a table EMP in which the values will be like this

EmpId Ename Sal DeptId
11 Ram 10000 10
11 Ram 10000 10
22 Raj 20000 20
22 Raj 20000 20
33 Anil 15000 30
33 Anil 15000 30

I want to delete only duplicate Rows. After Delete I want
the output like this

EmpId Ename Sal DeptId
11 Ram 10000 10
22 Raj 20000 20
33 Anil 15000 30



Answer Posted / shankar

First Of All Create Table
create table EMP(empid int, ename varchar(10),sal int,
deptid int)

insert into EMP values(11, 'Ram', 10000, 10)
insert into EMP values(11, 'Ram',10000,10)
insert into EMP values(22, 'Raj', 20000, 20)
insert into EMP values(22, 'Raj', 20000, 20)
insert into EMP values(33, 'Anil', 15000, 30)
insert into EMP values(33, 'Anil', 15000, 30)
insert into EMP values(44,'bbb',11111,40)
--Now Run This query It works
Declare @empID int, @RecCount int,@Name varchar (10),@Sal
int, @deptid int
SET @RecCount = 0
Declare MyCur Cursor for
Select empid,ename Sal,DeptID,Count(ID)-1 as Records from
EMP Group BY empid,ename Sal,DeptID having Count(empid)>1
Open MyCur
Fetch FROM MyCur INTO @empID,@Name,@sal,@DeptID,@RecCount

WHILE @@FETCH_STATUS = 0
BEGIN
SET ROWCOUNT @RecCount

DELETE from EMP where empID= @empID
SET @empID= 0
SET @Name = ''
SET @Sal= 0
SET @DeptID = 0
SET @RecCount = 0
SET ROWCOUNT 0
Fetch FROM MyCur INTO @empID,@Name,@sal,@DeptID,@RecCount
END

Close MyCur
DEallocate MyCur

Is This Answer Correct ?    3 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to delete multiple rows with one delete statement in ms sql server?

693


Name 3 ways to get an accurate count of the number of records in a table?

755


What the different topologies in which replication can be configured?

719


What is 2nf in normalization?

742


What is the report model project?

122






Define the one-to-one relationship while designing tables.

684


How to query multiple tables jointly?

707


Do you know what is recursion? Is it possible for a stored procedure to call itself or recursive stored procedure? How many levels of sp nesting is possible?

773


What is normalization? Describe its different types.

764


How to grant a permission in ms sql server using "grant execute" statements?

759


How to convert a numeric expression from one data type to another?

695


How will you monitor replication latency in transactional replication? : sql server replication

811


How important do you consider cursors or while loops for a transactional database?

702


What does <> symbol mean?

703


What is the significance of master, tempdb and model databases?

704