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
What command do we use to rename a database?
Can you pass expressions to stored procedure parameters?
What stored by the model? : sql server database administration
What is ddl and dml commands?
What command must you use to include the not null constraint after a table has already been created?
What is use of except clause?
How do you send email on SQL Server?
How to insert multiple rows with a subquery?
Do you know what are various aggregate functions that are available?
How can you start sql server in different modes?
How to view existing indexes on an given table using sp_help?
What command would you use to create an index?
Tell me about pre-defined functions of sql?
Explain the difference between primary keys and foreign keys?
What are the 7 disadvantages to a manual system?