Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

Iam working on SQLserver 2005 database using asp.net c#.

In my table i have 5 rows when i click on delete button it should delete first all rows except last row.

This table is incrementable, it will add rows.

This is my asp.net C# code.

C#
SqlConnection conDelete = new SqlConnection(_connString);
            SqlCommand cmdDelete = new SqlCommand();
            cmdDelete.Connection = conDelete;
          
            cmdDelete.CommandText = "Delete from UserTable where Id in (select top 3 Id from UserTable ORDER by Id asc)";
            using (cmdDelete)
            {
                conDelete.Open();

                cmdDelete.ExecuteNonQuery();
                conDelete.Close();

            }



Please help, thanks in advance.
Posted
Updated 12-Jan-14 19:37pm
v2

This will delete all the rows except the last row.
SQL
Delete from UserTable where Id not in (select Id from UserTable ORDER by Id desc)";
 
Share this answer
 
If you just want to delete all rows except the last one. You can use MAX(..) function.
Write a SQL like this, deletes all rows where Id is less than max.

SQL
DELETE FROM UserTable WHERE Id < (SELECT MAX(Id) FROM UserTable)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900