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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:05:13  来源:igfitidea点击:

Returning rows affected from an SQL UPDATE statement

c#asp.netsql-server-2008

提问by bluenose1970

Possible Duplicate:
SQL: Update a row and returning a column value with 1 query
Get affected rows on ExecuteNonQuery

可能的重复:
SQL:更新一行并返回带有 1 个查询的列值
在 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 InfoMessagebut 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();