如果没有行受到影响,.net SqlCommand.ExecuteNonQuery() 应返回什么值?

发布于 2024-09-03 08:31:26 字数 1003 浏览 4 评论 0原文

我有以下代码:

int result = -1;
StringBuilder sb = new StringBuilder();
SqlCommand cmd = MyConnection.
sb.AppendLine("delete from Table1 where ID in");
sb.AppendLine("(select id from Table1 t1 where  not exists(select * from Table2 t2 where t2.Table1ID = t1.ID))");
cmd.CommandText = sb.ToString();
result = cmd.ExecuteNonQuery();
_log.Info("StoredXMLDocument Records Deleted: " + result.ToString());

该 SQL 以更易读的格式表示为:

delete from Table1 where ID in
(select id from Table1 t1 where  not exists(select * from Table2 t2 where t2.Table1ID = t1.ID))

我知道该 SQL 在直接在数据库中执行时不会删除任何行。但是,当此代码运行时,结果的值为 1。我原以为它是 0。表 1 上没有触发器。我错过了什么吗?为什么是1?

附录:好的,现在当我在数据库中运行sql时,它会删除一行。请注意,在所有测试之前,我从为此目的保存的备份中恢复数据库。我发誓今天早上或昨天下午它没有删除任何行,是的,那是在恢复备份之后。我会让我的疯狂药丸失效,并在今天下午重新讨论这个问题。希望头脑更加清晰。

I have the following code:

int result = -1;
StringBuilder sb = new StringBuilder();
SqlCommand cmd = MyConnection.
sb.AppendLine("delete from Table1 where ID in");
sb.AppendLine("(select id from Table1 t1 where  not exists(select * from Table2 t2 where t2.Table1ID = t1.ID))");
cmd.CommandText = sb.ToString();
result = cmd.ExecuteNonQuery();
_log.Info("StoredXMLDocument Records Deleted: " + result.ToString());

That SQL, in a more readable format, is:

delete from Table1 where ID in
(select id from Table1 t1 where  not exists(select * from Table2 t2 where t2.Table1ID = t1.ID))

I know that the SQL, when executed directly in the database, deletes no rows. When this code runs, however, result gets a value of 1. I was expecting it to be 0. There are no triggers on Table1. Am I missing something? Why is it 1?

Addendum: ok, now when I run the sql in the database, it deletes a row. Note that before all tests, I restore the database from a backup I saved just for this purpose. I swear it wasn't deleting any rows this morning or yesterday afternoon, and yes that was after restoring the backup. I'm going to let me crazy pills wear off, and revisit the issue this afternoon. With a hopefully clearer mind.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

祁梦 2024-09-10 08:31:26

它应该返回0

尝试比较 DELETE 之前和之后的 SELECT COUNT(*) Table1

It should return 0.

Try comparing SELECT COUNT(*) Table1 before and after the DELETE.

孤城病女 2024-09-10 08:31:26

附带说明一下,您的查询可以简化为:

delete from Table1 where ID not in (select Table1ID from Table2)

出于兴趣尝试此查询:

delete from Table1 where 1 = 0 --we know this will delete no rows

另外,请确认 Table1 上是否有任何触发器。

As a side note, your query can be simplified to:

delete from Table1 where ID not in (select Table1ID from Table2)

Try this one for interest's sake:

delete from Table1 where 1 = 0 --we know this will delete no rows

Also, please confirm whether there are any triggers on Table1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文