如何删除数据表中的所有行
我想从数据表中删除 rowstate 属性值已删除的所有行。
DataTable dt;
dt.Clear(); // this will not set rowstate property to delete.
目前我正在迭代所有行并删除每一行。
有什么有效的办法吗? 我不想在 SQL Server 中删除我想使用 DataTable 方法。
I want to delete all rows from datatable with rowstate property value Deleted.
DataTable dt;
dt.Clear(); // this will not set rowstate property to delete.
Currently I am iterating through all rows and deleting each row.
Is there any efficient way?
I don't want to delete in SQL Server I want to use DataTable method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我们正在使用这种方式:
We are using this way:
这将满足任何 FK 级联关系,例如“删除”(DataTable.Clear() 不会):
This will satisfy any FK cascade relationships, like 'delete' (that DataTable.Clear() will not):
我通常执行以下 SQL 命令:
I typically execute the following SQL command:
由于您使用的是 SQL Server 数据库,我建议只需执行 SQL 命令
"DELETE FROM " + dt.TableName
。Since you're using an SQL Server database, I would advocate simply executing the SQL command
"DELETE FROM " + dt.TableName
.我会删除该表,这是删除所有内容的最快方法。然后重新创建表。
I would drop the table, fastest way to delete everything. Then recreate the table.
您可以在 SQL Server 数据库上创建一个存储过程,删除表中的所有行,从 C# 代码执行它,然后重新查询数据表。
You could create a stored procedure on the SQL Server db that deletes all the rows in the table, execute it from your C# code, then requery the datatable.
这是我在搜索这个问题后在自己的代码中确定的解决方案,并从 Jorge 的答案中获得灵感。
这样,您可以确保所有行都被删除,或者将其 DataRowState 设置为已删除。
此外,您不会因在枚举时修改集合而收到 InvalidOperationException,因为未使用
foreach
。然而,Jorge 的解决方案容易受到的无限循环错误在这里并不是问题,因为代码将增量超过其 DataRowState 已设置为已删除的 DataRow。Here is the solution that I settled on in my own code after searching for this question, taking inspiration from Jorge's answer.
This way, you ensure all rows either get deleted, or have their DataRowState set to Deleted.
Also, you won't get the InvalidOperationException due to modifying a collection while enumerating, because
foreach
isn't used. However, the infinite loop bug that Jorge's solution is vulnerable to isn't a problem here because the code will increment past a DataRow whose DataRowState has already been set to Deleted.