如果没有行受到影响,.net SqlCommand.ExecuteNonQuery() 应返回什么值?
我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它应该返回
0
。尝试比较
DELETE
之前和之后的SELECT COUNT(*) Table1
。It should return
0
.Try comparing
SELECT COUNT(*) Table1
before and after theDELETE
.附带说明一下,您的查询可以简化为:
出于兴趣尝试此查询:
另外,请确认
Table1
上是否有任何触发器。As a side note, your query can be simplified to:
Try this one for interest's sake:
Also, please confirm whether there are any triggers on
Table1
.