One DELETE request, how do you know that there was nothing to delete?

I am now polishing a C # application in relation to the SQL-Server database.

It is quite simple, you can add or remove records from the SQL table through some fields from the application.

Question: In the Delete action, I made this request:

DELETE FROM table WHERE ID = @ID 

It deletes what I ask to delete, BUT what if the query does not find anything in the database? How can I detect this? Since in this case the application does not delete anything, and an exception does not occur. To keep it short, I just wanted to tell the user that in this case nothing is deleted.

+4
source share
3 answers

If you use the SqlCommand object, there is an ExecuteNonQuery method. The method returns the number of rows. Thus, zero means no.

 private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); int rowsAffected = command.ExecuteNonQuery(); // <== this } } 
+11
source
 delete from table where ID=@id select @@rowcount 

This will return how many rows are really deleted. You do not need existence.

+3
source

Source: https://habr.com/ru/post/1435455/


All Articles