Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I want to delete all the rows of a table so i use the following code in my project:-
C#
public int DeleteALL()
      {

          SqlCommand cmd = new SqlCommand(cn);
          cmd.CommandText="Truncate Table TempMonth";
              

          int i = -1;
          try
          {
              i = cmd.ExecuteNonQuery();

          }

          catch (Exception ex)
          {
              this.error = ex.Message;

          }
          return i;
      } 


now my prob is.... all the rows from the table is deleted but the value of i is still -1. That means ExecuteNonQuery() doesn't return anything. what is the prob here anyone please give answer.
Posted
Updated 30-Aug-11 23:53pm
v2

The query will return -1 rather than a count.

As per msdn documentation[^],
"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1."
 
Share this answer
 
v3
Comments
Uday P.Singh 31-Aug-11 6:05am    
exactly my 5!
Abhinav S 31-Aug-11 6:06am    
Thanks.
Anil Honey 206 31-Aug-11 6:18am    
its Correct.
AFAIK: For UPDATE, INSERT, and DELETE statements, ExecuteNonQuery() returns the number of rows affected by the command.

For all other types of statements, the return value is -1.

And here you are using truncate not UPDATE, INSERT, and DELETE.

hope it helps :)
 
Share this answer
 
Comments
Abhinav S 31-Aug-11 6:04am    
Same answer as me. My 5.
Uday P.Singh 31-Aug-11 6:13am    
yeah Abhinav , it's a great coincidence and thanks for 5
No, you are slightly confused. TRUNCATE TABLE does not have a return value, so the ExecuteNonQuery returns -1.
If you set your initial value of i to 1234 instead of -1, you will see what I mean.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900