如何删除表中的第一行但不删除sqlserver 2005中的最后一行 [英] how to delete first rows in the table but not the last row in sqlserver 2005

查看:100
本文介绍了如何删除表中的第一行但不删除sqlserver 2005中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我使用asp.net c#在SQLserver 2005数据库上工作。



在我的表中我有5行,当我点击删除按钮时,它应该首先删除除最后一行之外的所有行。



此表是可递增的,它将添加行。



这是我的asp.net C#代码。



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.

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.

推荐答案

这将删除除最后一行之外的所有行。

This will delete all the rows except the last row.
Delete from UserTable where Id not in (select Id from UserTable ORDER by Id desc)";


如果你只是想要删除除最后一行之外的所有行。你可以使用MAX(..)函数。

写一个像这样的SQL,删除Id小于max的所有行。



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.

DELETE FROM UserTable WHERE Id < (SELECT MAX(Id) FROM UserTable)


这篇关于如何删除表中的第一行但不删除sqlserver 2005中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆