C# 返回受 SQL UPDATE 语句影响的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14505011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning rows affected from an SQL UPDATE statement
提问by bluenose1970
Possible Duplicate:
SQL: Update a row and returning a column value with 1 query
Get affected rows on ExecuteNonQuery
I have a textbox where the users enter their SQL queries.
我有一个文本框,用户可以在其中输入他们的 SQL 查询。
On example query could be:
示例查询可能是:
UPDATE customer SET isnew = 1;
Running the above query updates 4 rows, how do I get the '4 rows affected'message that which be returned by SQL Server.
运行上述查询更新 4 行,如何获取SQL Server 返回的“4 行受影响”消息。
I've tried using InfoMessage
but this only returns messages like 'Changed database context to 'databasenamehere'and not the actual rows affected.
我试过使用,InfoMessage
但这只会返回诸如“将数据库上下文更改为“数据库名称”之类的消息,而不是实际受影响的行。
回答by Rich
its not going to get the message you're after, but this will get the same count:
它不会得到你想要的消息,但这会得到相同的计数:
declare @RC int
(your statement here)
SELECT @RC = @@ROWCOUNT
That will give you the rowcount of the statement.
这将为您提供语句的行数。
回答by Eren Ers?nmez
SqlCommand.ExecuteNonQueryreturns the number of records affects as int
:
SqlCommand.ExecuteNonQuery返回记录数影响为int
:
var command = new SqlCommand("UPDATE customer SET isnew = 1;", conn);
int recordsAffected = command.ExecuteNonQuery();