Link to home
Start Free TrialLog in
Avatar of soft_ware
soft_ware

asked on

How to write a query to delete selected Rows?

Suppose I have a table having a following information:
        Name       Age     Sex
        ABC        12       M
        ABC        12       M
        ABC        12       M
        ABC        12       M
Now I want to write a query to delete all rows and retain one row.How?
       
 
Avatar of nigelrivett
nigelrivett

select distinct * into #a from tbl

begin tran
delete tbl
insert tbl select * from #a
commit tran

put in your own error processing


or

set rowcount 1
while 1 > (select count(*) from tbl)
   delete tbl
set rowcount 0

or
set rowcount 3
delete tbl
set rowcount 0



or
declare @sql varchar(1000), @cnt int
select @cnt = count(*) - 1 from tbl

select @sql = 'set rowcount ' + convert(varchar(10),@cnt) + ' delete tbl'

exec (@sql)
set rowcount 1
while 1 > (select count(*) from tbl)
  delete tbl
set rowcount 0


s.b.

set rowcount 1
while 1 < (select count(*) from tbl)
  delete tbl
set rowcount 0
Hi Soft_ware,

There is one problem with this approach.

You do not have any primary key.

SQL Server cannot handle duplicate records in a table structure.

So you will first need to change the DDL of the table structure.
[Add an identity column - int [Autonumber]]
   
Pri.Key  Name       Age     Sex
 1      ABC        12       M
 2      ABC        12       M
 3      ABC        12       M
 4      ABC        12       M
Then issue your delete statement: delete from <table> where Pri.Key < (select max(Pri.Key) from <table>)

This will always leave the last record in the table.

It would be a good idea to have tables with Primary Keys - [Or a completly unique identifier for every record] otherwise the database will not function correctly.

One other technique : Issue a Unique Constraint on the Name column.

Your delete statement would be:
delete from <table> where Name < (select max(Name) from <table>) this would leave the last record in the table available for use.

Regards,

Dan.
Check this FAQ question:
"How can I delete duplicate rows?"
http://www.MSSQLCity.com/FAQ/Devel/DelDupRows.htm


With best regards,
Alexander Chigrik
http://www.MSSQLCity.com/ - all about MS SQL
(SQL Server Articles, FAQ, Scripts, Tips and Test Exams).
ASKER CERTIFIED SOLUTION
Avatar of modulo
modulo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial