开发者

Show how many rows were deleted

开发者 https://www.devze.com 2023-01-14 00:04 出处:网络
I use C# program and my database is in SQL server 2008. When user deleted some rows from database, I want to show him/her in windows application how many rows deleted.

I use C# program and my database is in SQL server 2008.

When user deleted some rows from database, I want to show him/her in windows application how many rows deleted.

I want to kn开发者_开发百科ow how I can send SQL message to C# and show it for user. For example when I deleted 4 rows from table, SQL show message like (4 row(s) affected). Now I want to send number 4 to my C# program. How can I do it? Thank you.


If you are using SqlCommand from your .NET application to perform your delete/update, the result of ExecuteNonQuery() returns the number of rows affected by the last statement of the command.

See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx.


If you're using the System.Data.SqlClient.SqlCommand.ExecuteNonQuery method or System.Data.Common.DbCommand.ExecuteNonQuery method, then the return value should be the number of rows affected by your statement (the last statement in your command, I think).

There is a caveat to this...if you execute a batch or stored procedure that does SET NOCOUNT ON, then the number of rows affected by each statement is not reported and ExecuteNonQuery will return -1 instead.

in T-SQL, there is a @@rowcount variable that you can access in order to get the number of rows affected by the last statement. Obviously you would need to grab that immediately after your DELETE statement, but I believe you could do a return @@rowcount within your T-SQL if you are using SET NOCOUNT ON.

Alternatives would be to return the value as an OUTPUT parameter, especially if you have a batch of multiple statements and you'd like to know how many rows are affected by each. Some people like to use the T-SQL RETURN statement to report success/failure, so you may want to avoid returning "number of rows affected" for consistency's sake.


I imagine you would want to do a select "count" on the delete statement before you issue the delete, then capture the number and manipulate it as needed.


Use the @@RowCount SQL Environment variable. You can return it from a Stored Procedure if you are using them.

0

精彩评论

暂无评论...
验证码 换一张
取 消